【问题标题】:Selecting records group by选择记录分组依据
【发布时间】:2014-01-30 16:49:53
【问题描述】:
CREATE TABLE #A (Type Char(20),ID INT, ID2 int,Address VARCHAR(10))
INSERT INTO #A (Type,ID, ID2,Address)
VALUES  ('Child',101,290,'CAT'),
       ('Child',102,290,'CAR'),
       ('Self',290,290,'CAT')
       ,('Spouse',103, 777,'DOE')
       ,('Self',777,777,'DOE')
       ,('Self',811,NULL,'yyy')

所以,ID 在#A 中是唯一的,ID2 是分组的,所以记录 1-3 在一组中,4-5 在一组中,依此类推。 我想在哪里显示所有“ID” (i) 对于每个组,如果所有记录的地址都相同,我想获取 type = 'self' 的 ID (ii)如果每个组,如果少数记录的地址不同,我想获取自己的ID和地址不同的其他记录的ID。 (iii) 如果没有组,即 ID2 为空,我想要记录的 ID。

所以,输出应该是

102
290
777
811 

消除 ID 101,因为 290 具有相同的地址并且它们属于同一组。 保持290,因为它是自我。

谢谢!

【问题讨论】:

    标签: sql group-by


    【解决方案1】:

    为了解决这类问题,我发现将条件转换为每行的标志/度量很有用。窗口函数对此非常有用。

    以下实现三个规则:

    select type, id, id2, address
    from (select a.*,
                 rank() over (partition by id2 order by AddressCnt desc) as AddressRank
          from (select a.*,
                       (case when max(address) over (partition by id2) =
                                  min(address) over (partition by id2)
                             then 1 else 0
                        end) as AddressSame,
                        count(*) over (partition by id2, Address) as AddressCnt
                from a
               ) a
         ) a
    where (AddressSame = 1 and type = 'self') or
          (AddressRank > 1 or type = 'self') or
          id2 is null;
    

    SQL Fiddle 是 here

    【讨论】:

      猜你喜欢
      • 2013-03-15
      • 1970-01-01
      • 2020-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      相关资源
      最近更新 更多