SQL CE:选择不同的,按另一列

时间:2017-03-25 18:29:53

标签: sql sql-server-ce

我正在试图弄清楚如何订购我得到的数据,我想做一个选择不同的(名称)并按ID排序:

var querythis = "SELECT distinct(exerVariName) as variants FROM Test WHERE date = @0 ORDER BY ID";

所以我不得不选择distinct(id),这有可能实现吗?

2 个答案:

答案 0 :(得分:1)

使用DISTINCT时,您无法通过选择列表中的列进行排序。

但是你也可以使用GROUP BY得到一个明显的结果:

SELECT exerVariName as variants 
FROM Test 
WHERE date = @0 
GROUP BY exerVariName
ORDER BY MIN(ID) -- or MAX(ID)

编辑:

如果CE不允许ORDER BY中的聚合函数,您可以尝试派生表(希望它是允许的):

SELECT variants 
FROM 
 ( 
    SELECT exerVariName as variants, MIN(ID) as minID -- or MAX(ID)
    FROM Test 
    WHERE date = @0 
    GROUP BY exerVariName
 ) AS dt
ORDER BY minID

答案 1 :(得分:1)

试试这个:

select exerVariName as variants,
    MIN(ID) as min_id
from Test
where date = @0
group by exerVariName
order by min_id