【问题标题】:Custom aggregations in SQLSQL 中的自定义聚合
【发布时间】:2018-10-19 22:44:37
【问题描述】:

我有一个名为行业的表。有6个字段。架构如下。

在这种情况下,我需要执行自定义聚合。数据库中有 22 个区域。需要进行两个自定义聚合:

  1. 需要将区域 1-17 合并为一个值为 00 的新区域。
  2. 区域 20 和 21 需要改成另一个区域,代码值为 99。

接下来是我对此总体框架的尝试。我假设创建一个新表是完成此操作的最简单方法。底部是预期结果的一个非常简短的示例。

 create table industry2
 (
 year char(4),
 qtr char(2),
 area char(6),
 industry char(3),
 ownership char(2),
 employment numeric(8,0)
 );

 INSERT INTO Industry2
 (year, qtr, area, industry, ownership, employment)
 SELECT year, qtr, area, (select sum (employment) from dbo.industry where area 
 = '01' or area = '02' and so on):

 2017    01    01   123000    1    456
 2017    01    02   123000    1    101
 2017    01    03   123000    1    103
 2017    01    01   134000    1      6
 2017    01    02   134000    1      7
 2017    01    03   134000    1     12
 2017    01    09   134000    1      1
 2017    01    01   144000    1     14
 2017    01    20   134000    1      7
 2017    01    21   134000    1      8

预期结果

 2017   01     00   123000    1    660
 2017   01     00   134000    1     26
 2017   01     00   144000    1     14
 2017   01     99   134000    1     15

【问题讨论】:

    标签: sql-server tsql ssms aggregate-functions


    【解决方案1】:

    您可以使用CASE WHEN 语句定义您的自定义GROUP BY 子句:

    select  [year], 
            [qtr],
            case when [area] in('20','21') then '99' when [area] between 1 and 17 then '00' end as [area], 
            [industry], 
            [ownership], 
            sum([employment]) as [employment_sum] 
    from industry2 
    group by  
        [year], 
        [qtr], 
        case when [area] in('20','21') then '99' when [area] between 1 and 17 then '00' end, 
        [industry], 
        [ownership] 
    

    结果:

    【讨论】:

    • 感谢您的帮助。不过,最后一项。如果我想让它成为我正在查询的表的一部分,如何做到这一点?
    • @Calflamesfann 由于group by 操作会改变数据粒度,因此不可能将其作为表的一部分。如果您需要对查询进行参数化,最好的办法可能是创建一个视图或表值函数
    • 最后一个。如果我需要将语句更改为区域在 1 到 17 之间的位置,而与区域 99(由 20 和 21 组成)无关,我是否执行以下操作。 select.... from industry where area = 'x' or area = 'y' group by...
    • @Calflamesfann 是的,如果要过滤数据集,可以在 group by 子句之前添加 where 条件,但请务必使用原始值(1-17、20、21 ) 而不是“新”的(99 和 00)
    猜你喜欢
    • 1970-01-01
    • 2011-05-21
    • 2018-10-15
    • 1970-01-01
    • 2016-09-27
    • 1970-01-01
    • 2021-12-08
    • 2016-10-12
    • 2015-01-08
    相关资源
    最近更新 更多