如何在SQL中使用Distinct with SubString?
我的查询是
SELECT
Distinct [Units Period]
FROM Table_Name
ORDER BY RIGHT([Units Period], 4) DESC , SUBSTRING([Units Period], 5, 2) DESC
但它没有用。
答案 0 :(得分:1)
错误是:ORDER BY items must appear in the select list if SELECT DISTINCT is specified.
使用GROUP BY
SELECT
[Units Period]
FROM
Table_Name
GROUP BY
[Units Period]
ORDER BY
RIGHT([Units Period], 4) DESC ,
SUBSTRING([Units Period], 5, 2) DESC
或在distinct之后添加所有列:
SELECT
distinct
[Units Period],
RIGHT([Units Period], 4),
SUBSTRING([Units Period], 5, 2)
FROM
Table_Name
ORDER BY
RIGHT([Units Period], 4) DESC ,
SUBSTRING([Units Period], 5, 2) DESC
答案 1 :(得分:0)
您可以将查询重写为:
Select [Units Period]
From (
SELECT
Distinct [Units Period]
FROM Table_Name) T
ORDER BY RIGHT([Units Period], 4) DESC , SUBSTRING([Units Period], 5, 2) DESC