SQL - Order by Max() on Alias - sql

I gather that I cannot get the MAX() on some alias that I have in the select statement in sql queries?
Example:
Select
CASE WHEN CompletionDate IS NOT NULL THEN DATEDIFF(d, CreatedDate, CompletionDate) ELSE NULL END AS DaysLong
from CombinedMastervw
WHERE CreatedDate Between '03/01/2019 23:59:59.991' AND '04/01/2019 23:59:59.991'
ORDER BY MAX(dayslong)
Thus my question is on MAX(dayslong), do I have to end up doing a Max with the same code in the SELECT statement?

You should be able to use the alias.
Try:
ORDER BY dayslong
Max(dayslong) would return the single maximum value in the table you are selecting, so you cannot order by it.

If you want the max() use top (1) and order by:
Select TOP (1) DATEDIFF(day, CreatedDate, CompletionDate) DaysLong
from CombinedMastervw
WHERE CreatedDate >= '2019-03-01' AND
CreatedDate < '2019-04-02'
ORDER BY dayslong DESC;
I changed the date comparisons so they are for full days. If you really want a few seconds before midnight, then you can change back to your version.

Related

SQL select query returning wrong order by DESC

This is my query which is not returning the correct result ordered by RegistrationDate Desc:
SELECT
Team,
CONVERT(VARCHAR(10), RegistrationDate, 103) AS RegistrationDate,
FormFilledAt, CreationBy
FROM
Table_Candidate_Info
WHERE
Status = 'Completed'
GROUP BY
Team, CONVERT(VARCHAR(10), RegistrationDate, 103), FormFilledAt, CreationBy
ORDER BY
RegistrationDate DESC
If I will use this query, it's returning the correct order by RegistrationDate Desc
select *
from Table_Candidate_Info
order by RegistrationDate desc
I want above first query should be RegistrationDate order by Desc with group by query
Try
order by CONVERT(VARCHAR(10),RegistrationDate,103) desc
or better if you want really keep order by date (and not text) try this:
select Team, CONVERT(VARCHAR(10),RegistrationDate,103) as RegistrationDate, FormFilledAt,CreationBy
from (
Select Team, cast(RegistrationDate as date) as RegistrationDate ,FormFilledAt,CreationBy
from Table_Candidate_Info
where Status='Completed'
group by Team,cast(RegistrationDate as date) ,FormFilledAt,CreationBy
) tmp
order by RegistrationDate desc
Note: if you want group by date + time remove cast… as date
use distinct and CONVERT(VARCHAR(10),RegistrationDate,103) in order by clause
Select distinct Team,CONVERT(VARCHAR(10),RegistrationDate,103)as RegistrationDate ,FormFilledAt,CreationBy
from Table_Candidate_Info where Status='Completed'
order by CONVERT(VARCHAR(10),RegistrationDate,103) desc
Note: You don't need group by since you are not using any aggregated function
The reason why results are not ordered by RegistrationDate when you convert it to a varchar in Select clause is because Order By clause is logically processed after evaluation of Select clause.
Now in first query when you write
Select * from Table_Candidate_Info order by RegistrationDate desc
[Though writing * in select list is a very bad practice] format of RegistrationDate still remains date in Select clause which holds true for further logical processing phase of Order By clause. Hence 31.01.2019 comes first and 31.12.2018 later.
But when you convert it to varchar(10) to get a required format then actually Order By clause is ordering a Varchar and not Date. Hence 31/12/2018 comes first and 31/01/2019 comes after it.
To resolve the problem if you want to retain the formatting of datetime/date column in Select but Order By with Date value then simply cast the datetime column back to Date in Order by clause.
Pseudo code as:
select CONVERT(VARCHAR(10),RegistrationDate,103) as RegistrationDate from
Table_Candidate_Info
order by cast(RegistrationDate as Date) desc -- cast it back to date
Demo Link here: https://rextester.com/WMLQL78387

SQL server: Get record with date closest to given date

I have a table dbo.studies with datetime column studydate
I want to query the database using the datetime variable givendate to find the record closest to the datetime in column studydate
Using:
SELECT TOP 1 *
FROM studies
WHERE studies.studydate < givendate
ORDER BY studies.studydate DESC
Will result in the record that is less and closest to givendate, but I need the record closest to givendate, regardless of whether it's less or more then studydate
Any thoughts on how to find it?
One method is:
SELECT TOP 1 s.*
FROM studies s
ORDER BY ABS(DATEDIFF(day, s.studydate, #givendate));
This uses DATEDIFF() to get the closest date. Note that this is using day for the difference. If your "dates" have a time component, you might want a different date part.
Note that this will not take advantage of indexes. A faster method (if you have the indexes) is a bit more complicated:
SELECT TOP (1) s.*
FROM ((SELECT TOP 1 s.*
FROM studies s
WHERE s.studydate <= #givendate
ORDER BY s.studydate DESC
) UNION ALL
(SELECT TOP 1 s.*
FROM studies s
WHERE s.studydate > #givendate
ORDER BY s.studydate ASC
)
) s
ORDER BY DATEDIFF(day, s.studydate, #givendate));
Although this is more complicated, each subquery can use an index on studydate. The final sort would have only two rows, so it should be really fast.
SELECT TOP 1 *
FROM studies
ORDER BY ABS(DATEDIFF(second, #givendate, studies.studydate))
use datediff function in order by it will always return the nearest 1
SELECT TOP 1 *
FROM studies
ORDER BY DATEDIFF(dd,studies.studydate, givendate) ASC
Order By ABS(DATEDIFF(day, YourDate, GetDate()))
Is The Best Method For Get Distinct and unique Recod When Your Table is Many Row and one column different
SELECT * FROM
(
SELECT *,
ROW_NUMBER() OVER (PARTITION BY ColumnName ORDER BY ABS(DATEDIFF(day, YourDate, GetDate()))) RowNumber
FROM [tableName]
)A
WHERE RowNumber = 1

Athena greater than condition in date column

I have the following query that I am trying to run on Athena.
SELECT observation_date, COUNT(*) AS count
FROM db.table_name
WHERE observation_date > '2017-12-31'
GROUP BY observation_date
However it is producing this error:
SYNTAX_ERROR: line 3:24: '>' cannot be applied to date, varchar(10)
This seems odd to me. Is there an error in my query or is Athena not able to handle greater than operators on date columns?
Thanks!
You need to use a cast to format the date correctly before making this comparison. Try the following:
SELECT observation_date, COUNT(*) AS count
FROM db.table_name
WHERE observation_date > CAST('2017-12-31' AS DATE)
GROUP BY observation_date
Check it out in Fiddler: SQL Fidle
UPDATE 17/07/2019
In order to reflect comments
SELECT observation_date, COUNT(*) AS count
FROM db.table_name
WHERE observation_date > DATE('2017-12-31')
GROUP BY observation_date
You can also use the date function which is a convenient alias for CAST(x AS date):
SELECT *
FROM date_data
WHERE trading_date >= DATE('2018-07-06');
select * from my_schema.my_table_name where date_column = cast('2017-03-29' as DATE) limit 5
I just want to add my little words here, if you have date column with ISO-8601 format, for example: 2022-08-02T01:46:46.963120Z then you can use parse_datetime function.
In my case, the query looks like this:
SELECT * FROM internal_alb_logs
WHERE elb_status_code >= 500 AND parse_datetime(time,'yyyy-MM-dd''T''HH:mm:ss.SSSSSS''Z') > parse_datetime('2022-08-01-23:00:00','yyyy-MM-dd-HH:mm:ss')
ORDER BY time DESC
See more other examples here: https://docs.aws.amazon.com/athena/latest/ug/application-load-balancer-logs.html#query-alb-logs-examples

SQL Server : select the minimum value from table

I know it's simple question, but I still can't figure it out.
I want to find the date which is the closest date from now.
Here is my product table:
P_INDATE
----------
2013-11-03
2013-12-13
2013-11-13
Basically, it should show 2013-12-13.
I type this SELECT Max( P_INDATE) FROM product and it work.
Then, I try to use MIN((GETDATE()- P_INDATE)) in the where condition, but I fail.
Use MAX and WHERE clause along with function GETDATE():
SELECT MAX(P_INDATE)
FROM product
WHERE P_INDATE < GETDATE()
The above query gives you maximum date, which is less than current date, which you get using function GETDATE()
One way to go about this is to order the query by the difference between the stored date and the current date and take the first rows only. Using abs will allow you to find the closest date regardless of whether its before or after the current date.
SELECT TOP 1 p_indate
FROM mytable
ORDER BY ABS(GETDATE() - p_indate) ASC
Assuming you have a column which stores data and you want to show only recent one every time,why cant you use
select max(date) from yourtable which will always give you recent date
If you have an index on the column, the most efficient method is probably a bit more complicated:
SELECT TOP 1 P_INDATE
FROM ((SELECT TOP 1 P_INDATE
FROM product
WHERE P_INDATE < GETDATE()
ORDER BY P_INDATE DESC
) UNION ALL
(SELECT TOP 1 P_INDATE
FROM product
WHERE P.INDATE >= GETDATE()
ORDER BY P.INDATE
)
)
ORDER BY ABS(DATEDIFF(second, P_INDATE, GETDATE()))
The subqueries will use the index to get (at most) one row earlier and later than the current date. The outer ORDER BY then just needs to sort two rows.
Well you can try this:
SELECT TOP(1) P_INDATE
FROM [product table]
ORDER BY CASE
WHEN DATEDIFF(day,P_INDATE,GETDATE()) < 0
THEN DATEDIFF(day,GETDATE(),P_INDATE)
ELSE DATEDIFF(day,P_INDATE,GETDATE())
END ASC

Getting a value for the smallert interval

I have a SQL table similar to this:
Value StartDate EndDate
I need to get the value where the interval between StartDate and EndDate is the smallest of the whole table. How do I express it in a WHERE clause?
I am using SQL Server 2012.
Use this:
SELECT TOP 1 value
FROM tbl1
ORDER BY DATEDIFF(ms, StartDate, EndDate)
If you have mode than one row with minimum difference you can use this:
SELECT TOP 1 WITH TIES value
FROM tbl1
ORDER BY DATEDIFF(ms, StartDate, EndDate)
You should be able to use DateDiff() similar to this:
select value, startdate, enddate
from yourtable
where datediff(ss, startdate, enddate) = (select min(datediff(ss, startdate, enddate))
from yourtable)
See SQL Fiddle with Demo
SELECT TOP 1 Value
FROM YourTable
ORDER BY DATEDIFF(ms, StartDate, EndDate)
Note, there is no specification here about which Value to choose if there are multiple ones that have the same, minimum difference.
However, the DATEDIFF might not be great for performance if you have a larger number of rows in the table. If this is a frequent type of query, I would consider storing the difference as another column in the table and then use that to ORDER BY.