SQL - How to order by two columns [closed] - sql

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last year.
Improve this question
Imagine we have a table 'user' with several different column. Two of them are date (date) and isValid (boolean). I would like to write sql what sort this by two columns (date and isValid). First of all i would like to sort by date ASC, then every row what has isValid = 1 should be after all row with isValid = 0. So even if have a row with date = 2022.01.01 with isValid = 0 should be before row with date 2021.01.01
Initial Data:
Date IsValid
2023 0
2022 1
2025 0
2024 1
2026 0
Expected Data:
Date IsValid
2023 0
2025 0
2026 0
2022 1
2024 1

With a comma between the columns...
SELECT
date,
isValid
FROM
yourTable
ORDER BY
isValid,
date

based on your edit your ordering of column will be changed isvalid will come first then date so I changed my answer like below
order by isValid, date

You will need to specify desc for isValid column as it seems that you want true value records first, so your query would be like below:
SELECT * FROM `USER` ORDER BY `DATE`, ISVALID DESC;

Related

SQL - Lead function to get dates from next row [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 months ago.
Improve this question
I have a table with a date and value for example:
AccID Date Value
1 01/01/2007 10
1 01/02/2008 20
1 01/03/2009 40
I want to create a new table that starts from the date in row 1 and ends with the date in row 2 and so on.....for example
AccID Date DateEnd Value
1 01/01/2007 01/02/2008 10
1 01/02/2008 01/03/2009 20
1 01/03/2009 01/04/2050 40
Select
date,
isnull(lead(date) over (partition by accID order by date), '01/04/2050') as DateEnd,
value
from column A
I have tried this code but I can't seem to get the correct output. This is the output I am currently getting
AccID Date DateEnd Value
1 01/02/2008 01/02/2009 20
1 01/02/2009 01/03/2007 40
1 01/01/2007 01/04/2050 10
You are not getting any output, you are getting an error
Incorrect syntax near 'partition'.
You get the correct results when you correct the error
Select
date,
isnull(lead(date) over (partition by accID order by date), '01/04/2050') as DateEnd,
value
from column A
Edit: Do yourself some favours and apply the following:
Avoid the use of reserved words or if you "must" use them, surround the column or table name with [ ] e.g. [date], [value],[column]
Research the function you're going to use to make the most of what it has to offer, to simplify your queries e.g. See the documentaion for Lead
Use date formats that are unambiguous e.g. '2050-04-01' in preference to '01/04/2050'. The latter could be either 1st April or 4th January depending on where in the world you happen to be

SQL query to get time spent on specific statuses based on single datetime column [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I need to build a SQL query in which I can get time spent on multiple statuses (onHold,Waiting for customer,Resolved,Closed), so basically I do not want to include time spent on this statues and table looks like as below
So I need a query in which I can get actual time spent on ticket or time spent on status which I have mentioned so far I have tried below solutions and tried Cross APPLY but seems all did not help me as expected.
Tried below query so far and that gives me correct time spent on first status on-hold not after that:
SELECT t1.TICKETNUMBER,SUM(DATEDIFF(MINUTE,TICKETTIME,CloseTime)) as TotalMinutes
FROM [Admin].[TbtrnTicketHistory] t1
CROSS APPLY(SELECT TOP 1 TICKETTIME as CloseTime FROM [Admin].[TbtrnTicketHistory] t2 WHERE t1.TICKETNUMBER = t2.TICKETNUMBER and t2.TICKETHISTORYID > t1.TICKETHISTORYID ORDER BY t2.TICKETTIME) as t2
WHERE t1.CURRENTSTATUS_ANALYST not in('On-Hold','Waiting For Customer','Resolved','Closed') and t1.ticketnumber = '211135'
GROUP BY t1.TICKETNUMBER;
calculate difference between two times in two rows in sql
Calculate Time Difference Between Two Consecutive Rows
with SQL Server you can use those very usefull windowed functions LEAD and FIRST_VALUE :
select *
,[duration(sec)] = DATEDIFF(SECOND
,ticketTime
,LEAD(ticketTime,1,ticketTime)over(partition by ticketNumber order by ticketTime)
)
,[cumulative duration(sec)] = DATEDIFF( SECOND
, FIRST_VALUE(ticketTime)over(partition by ticketNumber order by ticketTime)
, ticketTime)
from (values
(1,cast('20211101 10:00:01' as datetime))
,(1,'20211101 10:00:33')
,(1,'20211101 10:01:59')
)T(ticketNumber,ticketTime)
ticketNumber
ticketTime
duration(sec)
cumulative duration(sec)
1
2021-11-01 10:00:01.000
32
0
1
2021-11-01 10:00:33.000
86
32
1
2021-11-01 10:01:59.000
0
118

Get the rows with the latest date for an ID [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
My table has multiple rows for each id, with a calculated score and the date the calculation was done. Simplifying, it looks like this:
id
calc_score
date
1
82
today
1
53
yesterday
1
92
last week
2
23
today
2
60
yesterday
2
73
last week
I need a query that returns only today's scores for each ID. I tried various combinations of group by and distinct on but didn't get very far.
What's the best way for doing this?
PG has several ways. A simple approach is window functions, row_number, rank, etc.
The following will answer the question in your title, to return the latest (last) row per id (by date), which is different than the body of your question.
WITH cte AS (
SELECT t.*
, row_number() OVER (PARTITION BY id ORDER BY date DESC) AS rn
FROM scores
)
SELECT * FROM cte
WHERE rn = 1
;
This just picks the (latest dated) first row for each id based on the date column descending. This also assumes the date column really contains date values or something orderable like a date.
To answer your question in the question body:
I need a query that returns only today's scores for each ID
more strictly, we could also do this:
SELECT *
FROM scores
WHERE date = current_date
;
If you want only today's scores, then you could use a direct comparison if the date has no time component:
where date = current_date
Or for either dates or timestamps:
where date >= current_date and date < current_date + interval '1 day'
If you want the most recent row per id, you would use distinct on:
select distinct on (id) t.*
from t
order by id, date desc;

Get last rows before certain value [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
In my table, I have a field RAZ (bit) whose value is 0 except at 5am, 1pm and 9pm when it's equal to 1. I would like to get the last rows in my table before RAZ is equal to 1.
Here is a sample data :
For exemple, the final request would display the row with idEvenement = 8454.
I will use this request in a stored procedure to compute indicators.
The RAZ field changes to 1 automatically, it means that the data has been reset.
I don't know if it's possible and how to do it.
You can use SQL Server windowing function LEAD to see if the next record's RAZ turns to 1 while it was 0 before. LEAD gets the next record based on RAZTime order. This returns ID = 8454 as the result
; WITH cte (ID, RAZTime, RAZ) AS (
SELECT 8456, convert(datetime, '13:01 pm'), 1
union SELECT 8455, convert(datetime, '13:00 pm'), 1
union SELECT 8454, convert(datetime, '12:59 pm'), 0
union SELECT 8453, convert(datetime, '12:58 pm'), 0
)
, q AS (
SELECT
*
, NextRAZ = LEAD (RAZ, 1, NULL) OVER (ORDER BY RAZTime)
FROM cte
)
SELECT *
FROM q
WHERE
RAZ = 0
AND NextRAZ = 1

How can I write this SQL query [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have a database table looks like this:
Group - Year - Value
-------------------------------
Group A 2018 200
Group A 2019 300
Group A 2020 400
Group B 2019 500
Group B 2020 300
I want to write a SQL query or something like that or a reporting tool to generate a report as below:
Group 2018 2019 2020
----------------------------------
Group A 200 300 400
Group B ---- 500 300
I tried different ways but still not sure how to do that? Anyone can help?
You can use conditional aggregation:
select group,
sum(case when year = 2018 then value end) as value_2018,
sum(case when year = 2019 then value end) as value_2019,
sum(case when year = 2020 then value end) as value_2020
from t
group by group;
Note that group is a really bad name for a column, because it is a SQL keyword. If this is the actual name, I would suggest you change it.