两列的SQL两个不同的WHERE条件

Mat*_*son 9 sql-server

如何返回两列各自使用不同WHERE批评的列?显然,这不起作用:

SELECT Name, COUNT(Column1) AS Total, COUNT(Column1) AS YearToDate
FROM Table1
WHERE Occurred_Date BETWEEN '2010-06-01' AND '2010-06-30' --Total
WHERE Occurred_Date BETWEEN '2010-01-01' AND '2010-06-30' --YearToDate
Run Code Online (Sandbox Code Playgroud)

这是我正在寻找的输出:

Name  | Total | YTD  
-------------------
Item1 | 2     | 3
Item2 | 4     | 8
Run Code Online (Sandbox Code Playgroud)

Tob*_*oby 14

如果为COUNT函数指定列名,则不会计算NULL值.

因此,简单的方法是使用CASE语句转换您不想要的值 NULL

SELECT
    Name,
    COUNT(CASE
            WHEN Occurred_Date >= '2010-01-01' AND Occurred_Date < '2011-01-01'
                THEN Occurred_Date
            ELSE NULL
            END) AS [YTD]
    COUNT(CASE
            WHEN Occurred_Date >= '2010-06-01' AND Occurred_Date < '2011-07-01'
                THEN Occurred_Date
            ELSE NULL
            END) AS [MTD]
FROM Table1
GROUP BY Name
Run Code Online (Sandbox Code Playgroud)

我不是100%肯定查询引擎会让你在COUNT中使用CASE(我甚至不确定你正在使用什么数据库平台),但它给你的想法.如果这种方式不起作用,您可以使用派生表编写查询,该表将为您提供相同的结果.

  • 如果您不想依赖Null行为,您可以始终只让case语句返回1或0并执行求和而不是计数. (2认同)

nic*_*ico 5

你也可以使用

SELECT m.count, ytd.count FROM 
   (SELECT COUNT( id ) count FROM table WHERE date BETWEEN '2010-06-01' AND '2010-06-30') m, 
   (SELECT COUNT( id ) count FROM table WHERE date BETWEEN '2010-01-01' AND '2010-06-30') ytd 
Run Code Online (Sandbox Code Playgroud)