SQL Join查询帮助

时间:2012-01-06 20:01:06

标签: sql sql-server-2008

目前,我有2个查询:

SELECT dateadd(month, x.MonthOffset,0) as [Month], SUM(x.itemcount) as [Total] FROM
    ( SELECT datediff(month,0, cna.impdate) as MonthOffset, count(*) as itemcount FROM myTable
      WHERE (emergency = 'Emergency') AND (impdate BETWEEN '" + fromDate + "' AND '" + toDate + "') 
      GROUP BY impdate ) x
      GROUP BY MonthOffset ORDER BY MonthOffset asc

SELECT dateadd(month, x.MonthOffset,0) as [Month], SUM(x.itemcount) as [Total] FROM
    ( SELECT datediff(month,0, cna.impdate) as MonthOffset, count(*) as itemcount FROM myTable
      WHERE (impdate BETWEEN '" + fromDate + "' AND '" + toDate + "') 
      GROUP BY impdate ) x
      GROUP BY MonthOffset ORDER BY MonthOffset asc

这将返回2列数据,每月包含项目数。

当存在没有紧急项目的月份时,我的问题就出现了。因为我将对象传递给第二个查询,如果从第一个查询中检索的列数与第二个查询不匹配,我将收到索引超出范围的错误。

如何将我的两个查询加在一起,以便我可以有3列 - 月份,紧急总计和项目总数?紧急总数可以是0或null。

1 个答案:

答案 0 :(得分:5)

我没有办法测试它,但我认为这应该可以满足您的需求:

SELECT dateadd(month, datediff(month,0, cna.impdate),0) as [Month], 
       count(*) as itemcount, 
       SUM(CASE WHEN emergency = 'Emergency' THEN 1 ELSE 0 END) AS EmergencyCount
FROM myTable
WHERE impdate BETWEEN '" + fromDate + "' AND '" + toDate + "'
GROUP BY dateadd(month, datediff(month,0, cna.impdate),0)
ORDER BY [Month] asc