我是sql的新手,我想从这个表中获取数据:
id pseudo amount date
1 test1 34 2015-09-16 09:21:51
2 test2 78 2015-09-14 09:21:51
3 test3 896 2015-10-01 09:21:51
4 test4 67 2015-11-16 09:21:51
5 test5 12 2015-09-23 09:21:51
6 test6 19 2015-09-09 09:21:51
我想在一个查询中获得最大amount
和最后3个lignes按日期排序的ligne ...我可以在2个查询中执行此操作,但我想要此问题的最佳选项。你能帮我吗 ?对不起我的英文:)
pseudo amount
test3 896
test4 67
test5 12
test1 34
test2 78
答案 0 :(得分:0)
根据您的假设数据,我们可以使用 MAX 条件和 CTE
来实现此目的declare @Table1 TABLE
(id int, pseudo varchar(5), amount int, date varchar(19))
;
INSERT INTO @Table1
(id, pseudo, amount, date)
VALUES
(1, 'test1', 34, '2015-09-16 09:21:51'),
(2, 'test2', 78, '2015-09-14 09:21:51'),
(3, 'test3', 896, '2015-10-01 09:21:51'),
(4, 'test4', 67, '2015-11-16 09:21:51'),
(5, 'test5', 12, '2015-09-23 09:21:51'),
(6, 'test6', 19, '2015-09-09 09:21:51')
;
;WITH CTE AS (
select *,
ROW_NUMBER()OVER(PARTITION BY TN ORDER BY TN) RW
from (
select id,
pseudo,
amount,
MAX(pseudo)OVER( ORDER BY amount desc )TN from @Table1 )T )
,cte2 as (
Select top 3 pseudo,
amount
from CTE
WHERE RW = 2 order by amount)
Select pseudo,amount from CTE WHERE RW = 1 AND pseudo <> 'test6'
UNION ALL
select pseudo,amount from cte2