分组,同时保持下一个记录

时间:2016-10-11 15:44:17

标签: sql sql-server

我有一个表(NerdsTable),其中包含一些数据:

-------------+-----------+----------------
id             name          school
-------------+-----------+----------------
1              Joe         ODU
2              Mike        VCU
3              Ane         ODU
4              Trevor      VT
5              Cools       VCU

当我运行以下查询时

SELECT id, name, LEAD(id) OVER (ORDER BY id) as next_id
    FROM dbo.NerdsTable where school = 'ODU';

我得到了这些结果:

[id=1,name=Joe,nextid=3] 
[id=3,name=Ane,nextid=NULL]

我想编写一个不需要静态检查

的查询
where school  = 'odu'

但是给出了与上面相同的结果。换句话说,我想在数据库中选择所有结果,并将它们正确分组,就好像我单独完成并运行查询:

SELECT id, name, LEAD(id) OVER (ORDER BY id) as next_id FROM dbo.NerdsTable where school = 'ODU';
SELECT id, name, LEAD(id) OVER (ORDER BY id) as next_id FROM dbo.NerdsTable where school = 'VCU';
SELECT id, name, LEAD(id) OVER (ORDER BY id) as next_id FROM dbo.NerdsTable where school = 'VT';

以下是我希望看到的输出:

[id=1,name=Joe,nextid=3] 
[id=3,name=Ane,nextid=NULL]
[id=2,name=Mike,nextid=5] 
[id=5,name=Cools,nextid=NULL]
[id=4,name=Trevor,nextid=NULL] 

这是我尝试过的,但我失败了:

SELECT id, name,
    LEAD(id) OVER (ORDER BY id) as next_id
    FROM dbo.NerdsTable
    ORDER BY school;

-- Problem, as this does not sort by the id. I need the lowest id first for the group

SELECT id, name,
    LEAD(id) OVER (ORDER BY id) as next_id
    FROM dbo.NerdsTable
    ORDER BY id, school;

-- Sorts by id, but the grouping is not correct, thus next_id is wrong

然后我在Microsoft doc site上查看了聚合函数,但是没有看到我如何使用any来正确地对结果进行分组。我尝试使用GROUPING_ID,如下所示:

SELECT id, GROUPING_ID(name),
    LEAD(id) OVER (ORDER BY id) as next_id
    FROM dbo.NerdsTable
    group by school;

但是我收到了一个错误:

is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

知道我在这里缺少什么吗?

2 个答案:

答案 0 :(得分:1)

从您想要的输出看起来您只是想按学校订购记录。你可以这样做:

SELECT id, name
FROM dbo.NerdsTable
ORDER BY school ASC, id ASC

我不知道下一个ID应该是什么意思。

答案 1 :(得分:0)

{{1}}