0

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.

4

1 回答 1

3

DISTINCT不允许任何ORDER BY不在SELECT列表中的表达式(即使在这种情况下,表达式只能为每个不同的行产生一个特定值)。您可以使用。

SELECT Batchno,
       LocationId
FROM   Ordertbl
GROUP  BY Batchno,
          LocationId
ORDER  BY CASE
            WHEN[LocationId] = 3 THEN 0
            ELSE 1
          END,
          [LocationId] 
于 2012-10-09T07:21:10.487 回答