I have a datetime column from which I want to show the dates with format "dd/mm/yyyy"
I tried with
Select distinct CONVERT(VARCHAR(10), [DateAndTime], 103) as [DateAndTime]
from dbo.Prod
order by dbo.Prod.[DateAndTime]
but it gives me the error:
ORDER BY items must appear in the select list if SELECT DISTINCT is specified
If i exclude the last line it gives me a result like this
DateAndTime
03/03/2023
16/02/2023
17/02/2023
21/02/2023
What can I do to have this result ordered by the original column date format?
2条答案
按热度按时间nvbavucw1#
You can use group by instead of DISTINCT to do it:
As other say though, this is usually better to do on frontend side of things
zwghvu4y2#
You need to order by the column name in the
SELECT
, rather than a column from one of the tables, as once you haveDISTINCT
you effectively have aGROUP BY
on all columns. So you need to drop the table reference in theORDER BY
.Note however that this is inefficient, because you are not able to use indexes. Furthermore,
DISTINCT
is usually a code-smell, as it often indicates poor data.You can group by a conversion to
date
insteadOr if you use
GROUP BY
then you can place it in aCROSS APPLY
to avoid having to specify it multiple times.