0

我有一个联合所有查询。但在我的结果集中,我有 2 条 P1 记录和 3 条 P2 记录。即使没有值,我仍想显示 3 个 P3 记录。

请在下面查看我的代码

SELECT 'P1'     AS Priority,
       Count(*) Total,
       CONVERT(VARCHAR(5), Datepart(yyyy, logdate))
       + RIGHT('00'+ CONVERT(VARCHAR(5), Datepart(mm, logdate)), 2)
FROM   dbo.mg_rpt_calls
WHERE  priority = 'P1'
       AND CONVERT(VARCHAR(5), Datepart(yyyy, logdate))
           + RIGHT('00'+ CONVERT(VARCHAR(5), Datepart(mm, logdate)), 2) BETWEEN
               CONVERT(VARCHAR(5), Datepart(yyyy, Getdate()))
               + RIGHT(
               '00'+ CONVERT(VARCHAR(5), Datepart(mm, Getdate())-2), 2)AND
               CONVERT(
               VARCHAR(5), Datepart(yyyy, Getdate()))
               +
               RIGHT
               ('00'+ CONVERT(VARCHAR(5), Datepart(mm, Getdate())), 2)
GROUP  BY CONVERT(VARCHAR(5), Datepart(yyyy, logdate))
          + RIGHT('00'+ CONVERT(VARCHAR(5), Datepart(mm, logdate)), 2)
UNION ALL
SELECT 'P2'     AS Priority,
       Count(*) Total,
       CONVERT(VARCHAR(5), Datepart(yyyy, logdate))
       + RIGHT('00'+ CONVERT(VARCHAR(5), Datepart(mm, logdate)), 2)
FROM   dbo.mg_rpt_calls
WHERE  priority = 'P2'
       AND CONVERT(VARCHAR(5), Datepart(yyyy, logdate))
           + RIGHT('00'+ CONVERT(VARCHAR(5), Datepart(mm, logdate)), 2) BETWEEN
               CONVERT(VARCHAR(5), Datepart(yyyy, Getdate()))
               + RIGHT(
               '00'+ CONVERT(VARCHAR(5), Datepart(mm, Getdate())-2), 2)AND
               CONVERT(
               VARCHAR(5), Datepart(yyyy, Getdate()))
               +
               RIGHT
               ('00'+ CONVERT(VARCHAR(5), Datepart(mm, Getdate())), 2)
GROUP  BY CONVERT(VARCHAR(5), Datepart(yyyy, logdate))
          + RIGHT('00'+ CONVERT(VARCHAR(5), Datepart(mm, logdate)), 2)
ORDER  BY CONVERT(VARCHAR(5), Datepart(yyyy, logdate))
          + RIGHT('00'+ CONVERT(VARCHAR(5), Datepart(mm, logdate)), 2) 

我的结果集如下

Priority Total (No column name)
P2       9     201209
P2       15    201210
P1       1     201210
P1       1     201211
P2       5     201211

谢谢,迈克尔

4

1 回答 1

0

我认为您想在较低级别使用 group by,例如:

SELECT Priority, Count(*) Total,
       CONVERT(VARCHAR(5), Datepart(yyyy, logdate)) + RIGHT('00'+ CONVERT(VARCHAR(5), Datepart(mm, logdate)), 2)
FROM   dbo.mg_rpt_calls
WHERE  CONVERT(VARCHAR(5), Datepart(yyyy, logdate))
           + RIGHT('00'+ CONVERT(VARCHAR(5), Datepart(mm, logdate)), 2) BETWEEN
               CONVERT(VARCHAR(5), Datepart(yyyy, Getdate()))
               + RIGHT(
               '00'+ CONVERT(VARCHAR(5), Datepart(mm, Getdate())-2), 2)AND
               CONVERT(VARCHAR(5), Datepart(yyyy, Getdate())) +
               RIGHT('00'+ CONVERT(VARCHAR(5), Datepart(mm, Getdate())), 2)
group by Priority, CONVERT(VARCHAR(5), Datepart(yyyy, logdate)) + RIGHT('00'+ CONVERT(VARCHAR(5), Datepart(mm, logdate)), 2)

您可以选择包含另一个where子句或having具有priority in ('P1', 'P2', 'P3').

于 2012-11-19T22:40:37.603 回答