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.
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