Sql server 使用交叉选择的Ms-Sql?
我对group by有一些疑问。我还有两个学校Id最低和最高收入。我分组并计算总收入。但我不知道如何使用交叉选择Sql server 使用交叉选择的Ms-Sql?,sql-server,tsql,select,Sql Server,Tsql,Select,我对group by有一些疑问。我还有两个学校Id最低和最高收入。我分组并计算总收入。但我不知道如何使用交叉选择 RowId SchoolId month maxEarning minEarning 1 1 1 1000 900 2 1 2 2000 300 3 1 3 1500 750
RowId SchoolId month maxEarning minEarning
1 1 1 1000 900
2 1 2 2000 300
3 1 3 1500 750
4 2 1 2000 500
5 2 2 1500 1000
6 3 1 2000 1000
答案是
school id 1 ==> diff second month and first month 2000 - 900 = 1100
school id 1 ==> diff third month and second month 1500 - 300 = 1200
school id 2 ==> diff second month and first month 1500 - 500 = 1000
school id 3 ==> diff first month only 2000
最后我想看到的是:
RowId SchoolId month maxEarning minEarning DiffWithGroup
1 1 1 1000 900 1000
2 1 2 2000 300 1100
3 1 3 1500 750 1200
4 2 1 2000 500 2000
5 2 2 1500 1000 1000
6 3 1 2000 1000 2000
如果您的SQL Server版本支持,
LAG
分析函数是一个选项:
SELECT
RowId, SchoolId, month, maxEarning, minEarning,
maxEarning - LAG(minEarning, 1, 0) OVER
(PARTITION BY SchoolId ORDER BY month) AS DiffWithGroup
FROM yourTable
ORDER BY RowId;
如果您的SQL Server版本支持,
LAG
分析功能是一个选项:
SELECT
RowId, SchoolId, month, maxEarning, minEarning,
maxEarning - LAG(minEarning, 1, 0) OVER
(PARTITION BY SchoolId ORDER BY month) AS DiffWithGroup
FROM yourTable
ORDER BY RowId;
对于SQL Server 2012及更高版本,您可以使用LAG()
对于SQL Server 2012及更高版本,可以使用LAG()
我们可以使用
LAG
函数来执行此操作-
select
RowId,
SchoolId,
month,
maxEarning,
minEarning,
DiffWithGroup = (maxEarning - lag(minEarning,1,0) over(partition by SchoolId order by month))
from YourTableName
在此处检查此函数-我们可以使用
LAG
函数来执行此操作-
select
RowId,
SchoolId,
month,
maxEarning,
minEarning,
DiffWithGroup = (maxEarning - lag(minEarning,1,0) over(partition by SchoolId order by month))
from YourTableName
在此处检查此功能-您使用的是
MySQL
还是SQL Server
?Microsoft SQL Server到目前为止您尝试了什么?您使用的是MySQL
还是SQL Server
?Microsoft SQL Server到目前为止您尝试了什么?