SQL Query(SQL Server 2008)从两个表和组结果中检索数据

时间:2011-05-29 22:22:22

标签: sql sql-server sql-server-2008

我有两个表(假设有两列:IDcategory)。我想从第一个表中检索记录,从第二个表中检索记录,按类别检索组结果(两个表中有相同的类别)并分别计算它们。例如:

第一张表:

ID | category
-------------
1 | category1
2 | category2
3 | category3
4 | category1
5 | category2

第二张表:

ID | category
--------------
a | category1
b | category2
c | category3
d | category3

我想获得如下结果:

category | count(id from 1 table) | count(id from 2 table)
------------------------------------------------------------
category1 |        2 |        1
category2 |        2 |        2
category3 |        1 |        3

我试试这个:

SELECT r.AFFECTED_ITEM as usluga,
       COUNT(r.ID) AS problemy,
       (SELECT COUNT(k.ID)
          FROM KNOWNERRORM1 k
         WHERE k.AFFECTED_ITEM = r.AFFECTED_ITEM
      GROUP BY k.AFFECTED_ITEM) AS znane_bledy<br>
FROM ROOTCAUSEM1 r
group by r.AFFECTED_ITEM

...但是在结果中应该有更少的记录(因为内部联接)。

当我使用完全加入时,它应该有更多的记录..

4 个答案:

答案 0 :(得分:3)

根据Siva的建议进行修改。

SELECT COALESCE(table1Grouped.Category, table2Grouped.Category) AS Category, COALESCE(table1Grouped.IDCount, 0) AS Table1IDCount, COALESCE(table2Grouped.IDCount, 0) AS Table2IDCount
FROM
(
    SELECT table1.category, COUNT(table1.ID) AS IDCount
    FROM table1
    GROUP BY table1.category
) AS table1Grouped
    FULL OUTER JOIN
(
    SELECT table2.category, COUNT(table2.ID) AS IDCount
    FROM table2
    GROUP BY table2.category
) AS table2Grouped
    ON
table1Grouped.category = table2Grouped.Category

答案 1 :(得分:0)

你可以试试这个......

SELECT Category, COUNT(Id) AS TableOneCount, 0 AS TableTwoCount
FROM Table1
UNION
SELECT Category, 0 AS TableOneCount, COUNT(Id) AS TableTwoCount
FROM Table2
GROUP BY Category

很抱歉,如果这不起作用,我在家,没有安装SQL Server或其他任何东西来测试它(我是那些不在家编码的程序员之一:-p)< / p>

答案 2 :(得分:0)

SELECT
  category,
  table1count = COUNT(CASE tableid WHEN 1 THEN 1 END),
  table2count = COUNT(CASE tableid WHEN 2 THEN 1 END)
FROM (
  SELECT 1, category
  FROM Table1
  UNION ALL
  SELECT 2, category
  FROM Table2
) x (tableid, category)
GROUP BY category

答案 3 :(得分:0)

选择类别,(从t1选择计数(id),其中t1.Category = t3.Category),(从t2中选择count(id),其中t2.Category = t3.Category) 从t3

t3包含

组别 产品组别 类别3