父子关系 - SQL

时间:2013-11-23 10:21:03

标签: sql sql-server tsql

我有一个有父母和子女产品的数据。

每个家长在他们的帐户上都有一个唯一的代码(P1)和一个链接代码(L1),并且父母的每个孩子都有一个单独的代码(C12),但他们共享相同的帐号。

我想计算父母和孩子的数量

这是一个示例数据集

create table #Something
(
   Line_no int,
   code varchar(5),
   AccountNo char(5)
)

一些示例数据

INSERT #Something
select 12311, 'P1c', 'Ac115' union all
select 12311, 'L1', 'Ac115' union all
select 123, 'C1', 'Ac115' union all
select 1222, 'C1', 'Ac115' union all
select 1243, 'C1', 'Ac115' union all
select 433, 'P1a', 'Ac111' union all
select 433, 'L1', 'Ac111' union all
select 4331, 'C1', 'Ac111' union all
select 543, 'C1', 'Ac222' union all
select 544, 'C1', 'Ac222' union all
select 4322, 'P1b', 'Ac222' union all
select 4322, 'L1', 'Ac222' union all

select 8766,'P1d' , 'Ab111' union all
select 8766,'L1' , 'Ab111' union all
select 8767,'C1', 'Ab111' union all
select 8789,'P1d', 'Ab119' union all
select 8766,'L1', 'Ab119' union all
select 876654,'C1', 'Ab119' union all
select 876655,'C1', 'Ab119' union all
select 876698,'P1a', 'Ab117' union all
select 876698,'L1', 'Ab117' union all
select 987,'C1', 'Ab117' union all
select 555444,'P1d','Xcv' union all
select 555444,'L1','Xcv' union all
select 6754,'C1','Xcv'

SELECT * from #Something

drop table #Something

所需的输出是:

[Parent code] [Parent line Count] [Child line Count]    
  P1c                1                   3
  P1a                2                   2
  P1b                1                   2
  P1d                3                   4 

由于

1 个答案:

答案 0 :(得分:0)

很奇怪的架构,但是这个查询会给你你想要的东西:

with cte as (
    select
        max(case when code like 'P%' then code end) as [Parent code],
        count(case when code like 'P%' then code end) as [Parent line Count],
        count(case when code like 'C%' then code end) as [Child line Count]
    from Something
    group by AccountNo
)
select
    [Parent code],
    sum([Parent line Count]) as [Parent line Count],
    sum([Child line Count]) as [Child line Count]
from cte
group by [Parent code] 

<强> sql fiddle demo

如果您不喜欢公用表表达式,可以使用子查询:

select
    [Parent code],
    sum([Parent line Count]) as [Parent line Count],
    sum([Child line Count]) as [Child line Count]
from (
    select
        max(case when code like 'P%' then code end) as [Parent code],
        count(case when code like 'P%' then code end) as [Parent line Count],
        count(case when code like 'C%' then code end) as [Child line Count]
    from Something
    group by AccountNo
) as A
group by [Parent code]