ORDER BY items must appear in the select list if SELECT DISTINCT is specified

半城伤御伤魂 提交于 2019-12-02 17:51:07

问题


I have sql query in which i want return rows with distinct value order by particular column. like say,i want disntict batchno from ordertable order by locationid.

i have tried google also but not able to find out solution

ORDER BY items must appear in the select list if SELECT DISTINCT is specified.

that what i got every time i tried.

when not using distinct i got output but with duplicate rows using this query

Select Batchno,LocationId from Ordertbl order by case when[LocationId] =3 THEN 0 ELSE 1 END, [LocationId]

if i use distinct it gives me error these are query i tried out.

Select distinct CAST(Batchno as Varchar(MAX)),LocationId from Ordertbl order by case when[LocationId] =3 THEN 0 ELSE 1 END,[LocationId]

or

Select distinct CAST(Batchno as Varchar(MAX)),LocationId from Ordertbl order by case when[LocationId] =3 THEN 0 ELSE 1 END,[LocationId],[Batchno]

so this is things i tried but no luck.please help me.


回答1:


DISTINCT doesn't allow any expression in the ORDER BY that is not also in the SELECT list (even if, as in this case, the expression could only yield one specific value for each distinct row). You can use.

SELECT Batchno,
       LocationId
FROM   Ordertbl
GROUP  BY Batchno,
          LocationId
ORDER  BY CASE
            WHEN[LocationId] = 3 THEN 0
            ELSE 1
          END,
          [LocationId] 


来源:https://stackoverflow.com/questions/12794751/order-by-items-must-appear-in-the-select-list-if-select-distinct-is-specified

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!