不同列的聚合计数

时间:2017-11-04 06:48:17

标签: sql-server tsql

有两个表:

表a

  id   name    b_id1    b_id2   b_id3   b_id4
    1   a        10      8      null     null
    2   b        3       4       8       10
    3   c        10      5       4      null

表B

    b_id      title
     3        Value3
     4        Value4
     5        Value 5
     8        Value 8
     10       Value
  

表A在b_id1上有F.K,b_id2,b_id3,b_id4到b_id cloumn上的表B,

我们将对Title进行分组并计算它。 类似于以下结果:

Title     Count
Value3     1
Value4     2
Value5     1
Value8     2
Value10    3
 Null      3

2 个答案:

答案 0 :(得分:1)

一种方式如下:Demo Here

;with cte
as
(select title,count(b_id) as val from table1 t
join
table2 t2
on t.id=t2.b_id
or
t.b_id1=t2.b_id
or      
t.b_id2=t2.b_id
or      
t.b_id3=t2.b_id
or      
t.b_id4=t2.b_id
group by title
)
select * from cte
union all

select null,sum(case 
when b_id1 is null then 1 else 0  end)+
sum(case 
when b_id2 is null then 1 else 0  end)
+sum(case 
when b_id3 is null then 1 else 0  end)
+sum(case 
when b_id4 is null then 1 else 0  end)

from table1

输出

Value   3
Value 5 1
Value 8 2
Value3  2
Value4  2
NULL    3

答案 1 :(得分:1)

完整的工作示例:

DECLARE @Table1 TABLE
(
     [id] INT
    ,[name] VARCHAR(1)
    ,[b_id1] INT
    ,[b_id2] INT
    ,[b_id3] INT
    ,[b_id4] INT
);

DECLARE @Table2 TABLE
(
    [b_id] INT
   ,[title] VARCHAR(7)
);

INSERT INTO @Table1 ([id], [name], [b_id1], [b_id2], [b_id3], [b_id4])
VALUES (1, 'a', 10, 8, NULL, NULL)
      ,(2, 'b', 3, 4, 8, 10)
      ,(3, 'c', 10, 5, 4, NULL);

INSERT INTO @Table2 ([b_id], [title])
VALUES (3, 'Value3')
      ,(4, 'Value4')
      ,(5, 'Value 5')
      ,(8, 'Value 8')
      ,(10, 'Value');

SELECT T2.[title]
      ,COUNT(*)
FROM
(
    SELECT [b_id1]
    FROM @Table1
    UNION ALL
    SELECT [b_id2]
    FROM @Table1
    UNION ALL
SELECT [b_id3]
FROM @Table1
UNION ALL
SELECT [b_id4]
FROM @Table1
) DS
LEFT JOIN @Table2 T2
    ON DS.[b_id1] = T2.[b_id]
GROUP BY T2.[title];

enter image description here