【问题标题】:Ms - Sql using cross select?女士 - 使用交叉选择的 Sql?
【发布时间】:2018-04-26 07:09:09
【问题描述】:

我对 group by 有一些疑问。我也有几所学校的最低和最高收入。我分组,我想计算总收入。但我不知道如何使用交叉选择。

 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

【问题讨论】:

  • 你使用的是MySQL还是SQL Server
  • 微软 Sql 服务器
  • 到目前为止你有什么尝试?

标签: sql-server tsql select


【解决方案1】:

LAG 分析函数是一种选择,如果您的 SQL Server 版本支持它:

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;

Demo

【讨论】:

    【解决方案2】:

    我们可以使用LAG 函数来做到这一点-

    select
        RowId,
        SchoolId,
        month,
        maxEarning,
        minEarning,
        DiffWithGroup = (maxEarning - lag(minEarning,1,0) over(partition by SchoolId order by month))
    from YourTableName
    

    在此处查看此功能 - LAG TSQL Function

    【讨论】:

      【解决方案3】:

      对于 SQL Server 2012 及更高版本,您可以使用 LAG()

      select  *,
              maxEarning - isnull(LAG(minEarning) over (partition by SchoolId 
                                                            order by month), 0) as DiffWithGroup
      from    your_table
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-17
        • 1970-01-01
        • 2012-08-29
        • 1970-01-01
        • 1970-01-01
        • 2013-10-05
        • 1970-01-01
        • 2013-01-02
        相关资源
        最近更新 更多