我有这张桌子
| date | sum |
|--------------|-------|
| 2015-02-19 | 10000 |
| 2015-02-19 | 10000 |
| 2015-02-20 | 15000 |
| 2015-02-20 | 15000 |
| 2015-02-21 | 18000 |
| 2015-02-21 | 18000 |
我想从表中选择前2行,但只选择不同的行,这意味着我的结果应该返回2015-02-20
和2015-02-21
。
SELECT TOP 2 distinct date
FROM stock
使用它会给我一个错误:
关键字' distinct'附近的语法不正确。
帮助将受到高度赞赏。
答案 0 :(得分:2)
您可以尝试这样
select top 2 * from
(
select distinct date FROM stock
)
答案 1 :(得分:2)
尝试类似:
SELECT TOP 2 date
FROM stock
GROUP BY date
答案 2 :(得分:2)
我认为Distinct和Top应该在您的查询中切换位置:
SELECT DISTINCT TOP 2 date FROM stock ORDER BY date DESC
答案 3 :(得分:1)
试
select distinct top 2 date from stock
答案 4 :(得分:1)
您可以使用GROUP BY
:
SELECT TOP 2 date
FROM stock
GROUP BY date
ORDER BY date DESC
示例结果:
DATE
2015-02-21
2015-02-20
请参阅SQL Fiddle中的结果。
答案 5 :(得分:0)
试试这个:
WITH cte AS
( SELECT distinct date ,
ROW_NUMBER() OVER (PARTITION BY date
ORDER BY date DESC
)
AS rn
FROM stock
)
SELECT date
FROM cte
WHERE rn <= 3
ORDER BY rn ;
答案 6 :(得分:0)
试试这个:
SELECT TOP 2 date FROM stock group by date