2

我正在尝试从 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)

我需要将 case 表中的状态与两个状态表中的状态 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

你知道该怎么做吗?

4

2 回答 2

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
于 2012-05-30T13:30:47.073 回答
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
于 2012-05-30T13:29:48.090 回答