如果没有显示记录,如何显示零或日期值

时间:2012-11-19 21:44:14

标签: sql tsql

我有一个联合所有查询。但在我的结果集中,我有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

谢谢, 迈克尔

1 个答案:

答案 0 :(得分:0)

我认为您希望在较低级别使用该组,例如:

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')子句。