从多个表中获取值,使用count和group by

时间:2012-05-30 13:18:25

标签: sql-server count group-by multiple-tables multiple-databases

我正在尝试在2个不同的数据库(全局和私有)中从3个不同的表(状态,状态和案例)输出MSSQL中的一些数据。

global.status    // contains labels for global status ID's
     fields (id, text)
private.status   // contains labels for private status ID's
     fields (id, text)
private.cases    // contain case information, such as status
     fields (status, count(status) AS amount)

我需要将案例表中的状态与两个状态表中的状态ID进行比较,并输出以下内容:

    statusID |    text     | amount
   ----------|-------------|--------
     9993    |    Open     |   24
     9991    |   Closed    |    3
     9992    |   Pending   |   12

拥有全局和私有的共鸣是私有允许自定义私有状态,其中全局可在整个系统中访问。

我对此失败的尝试是以下sql

SELECT  c.status, 
    COUNT(c.status) as amount, 
    ss.text,
    gs.text
FROM [DB11111111].dbo].[cases] AS c, [DB11111111].[dbo].[status] AS ss, [global].[dbo].[status] AS gs
WHERE (c.status = ss.id) OR (c.status = gs.id)
GROUP BY c.status, ss.text, gs.text 
ORDER BY amount DESC

你知道该怎么做吗?

2 个答案:

答案 0 :(得分:3)

SELECT  *
FROM    (
        SELECT  id, text
        FROM    private
        UNION ALL
        SELECT  id, text
        FROM    global
        ) q
CROSS APPLY
        (
        SELECT  COUNT(*) cnt
        FROM    cases
        WHERE   status = q.id
        GROUP BY
                status
        ) c

答案 1 :(得分:2)

如果它们是不同的,您可以联合/联合所有本地和全局状态:

SELECT  c.status, 
    COUNT(c.status) as amount, 
    s.text
FROM [DB11111111].dbo.[cases] AS c
LEFT JOIN
(
   select id, [text]
     from [DB11111111].[dbo].[status] 
   union all
   select id, [text]
     from [global].[dbo].[status]
) s
  ON c.Status = s.Id
GROUP BY c.status, s.Text
ORDER BY amount DESC

如果它们重叠,则需要定义哪一个优先,并在它们上使用完全外连接。

SELECT  c.status, 
    COUNT(c.status) as amount, 
    s.text
FROM [DB11111111].dbo.[cases] AS c
LEFT JOIN
(
   -- local before global
   select isnull (l.id, g.id) ID
          isnull (l.[text], g.[text]) [text]
     from [DB11111111].[dbo].[status] l
     full outer join [global].[dbo].[status] g
       on l.id = g.id
) s
  ON c.Status = s.ID
GROUP BY c.status, s.Text
ORDER BY amount DESC