在SQL中使用DISTINCT进行排序

时间:2014-03-20 11:01:29

标签: sql

我的查询如下:

SELECT DISTINCT Format(partycaseassociatedparty.assigneddate, 'MM/dd/yyyy') AS [*Assigned Date],
                Format(partycaseassociatedparty.releaseddate, 'MM/dd/yyyy') AS [*Released Date]
FROM   dbo.partycaseassociatedparty AS PartyCaseAssociatedParty
WHERE  partycaseassociatedparty.programid = 1
ORDER  BY [*assigned date] DESC

这里[*指定日期]是MM / dd / yyyy格式,所以在排序时(order by)它将根据MM / dd / yyyy进行排序,但我需要根据yyyy / MM / dd进行排序。如何实现这一目标?

2 个答案:

答案 0 :(得分:0)

ORDER BY  FORMAT(PartyCaseAssociatedParty.AssignedDate,'yyyy/MM/dd') DESC

答案 1 :(得分:0)

不使用distinct,而是使用group by

SELECT Format(pcap.assigneddate, 'MM/dd/yyyy') AS [*Assigned Date],
       Format(pcap.releaseddate, 'MM/dd/yyyy') AS [*Released Date]
FROM   dbo.partycaseassociatedparty AS pcap
WHERE  pcap.programid = 1
GROUP BY Format(pcap.assigneddate, 'MM/dd/yyyy'), Format(pcap.releaseddate, 'MM/dd/yyyy')
ORDER BY max(pcap.assigneddate) DESC;

使用group by时,可以在order by子句中使用聚合函数。