从2个不同的表中获取计数值

时间:2014-05-30 10:42:39

标签: sql sql-server sql-server-2008 sql-server-2005 sql-server-2008-r2

我正在使用Sql Server 2008.有3个表table1,table2,table3

表1,

Id  Name  group  
1   ddd   a       
2   aaa   b       
3   sss   a

table2包含:

Id Name group
1  fff   c
2  gg    a
3  saa   b

表3,

Id group
1  a
2  b
3  c

我想获得以下结果,

group     count(table1)   count(table2)
a           2               1
b           1               1
c           0               1

我可以写什么查询来获得适当的结果

4 个答案:

答案 0 :(得分:1)

您可以尝试这样

SELECT
   group,
   (SELECT COUNT(*) FROM table1 WHERE group=G.group)  AS table1count,
   (SELECT COUNT(*) FROM table2 WHERE group=G.group)  AS table2count
FROM table3 G

答案 1 :(得分:0)

试试这个:

SELECT T3.[group],
       COUNT(T1.[group]) as Count1,
       COUNT(T2.[group]) as Count2
FROM Table3 T3 LEFT JOIN
     Table1 T1 on T3.[group]=T1.[group] LEFT JOIN
     Table2 T2 on T3.[group]=T2.[group]
GROUP BY T3.[group]

结果:

GROUP   COUNT1  COUNT2
a       2       2
b       1       1
c       0       1

请参阅SQL Fiddle中的结果。

<强>解释

COALESCE将返回第一个非null的参数。因此,如果count为null,则返回0。

答案 2 :(得分:0)

insert into @table1 
values (1, 'aaa', 'a'),
(1, 'bbb', 'b'),
(1, 'ccc', 'c'),
(1, 'ddd', 'd')


insert into @table2 (id, name, groupcode) 
values (1, 'aaa', 'a'),
(1, 'bbb', 'b'),
(1, 'ddd', 'd')

insert into @table3 (id, name, groupcode) 
values (1, 'aaa', 'a'),
(1, 'bbb', 'b'),
(1, 'ccc', 'c'),
(1, 'ddd', 'd')

SELECT tab1.groupcode,
       COUNT(tab1.groupcode) as Count1,
       COUNT(tab2.groupcode) as Count2,
       COUNT(tab3.groupcode) as Count3
FROM @table1 tab1 
INNER JOIN @Table2 tab2 on tab1.groupcode = tab2.groupcode 
INNER JOIN @Table3 tab3 on tab1.groupcode = tab3.groupcode

/*
    USE LEFT JOINS IF YOU WANT TO RETURN ALL 
    GROUPS EVEN IF THERE IS NOT A MATCH IN
    ONE OF THE TABLES
*/


GROUP BY 
tab1.groupcode

答案 3 :(得分:0)

尝试使用CROSS APPLY

SELECT group, T1.T1Count, T2.T2Count
FROM   Groups G
CROSS APPLY
  (SELECT COUNT(*) AS T1Count FROM table1 AS IT1 WHERE G.group = IT1.group) T1
CROSS APPLY
  (SELECT COUNT(*) AS T2Count FROM table2 AS IT2 WHERE G.group = IT2.group) T2