两个SQL Server查询具有不同的where子句

时间:2017-10-14 19:37:09

标签: sql sql-server

我正在尝试合并两个非常相似的查询。唯一不同的是WHERE子句:

SELECT
    CONVERT(VARCHAR(10), Date, 101) as Date,
    COUNT(*) as WinnerCount
FROM
    table t1
WHERE
    t1.Result = 'Winner'
GROUP BY
    CONVERT(VARCHAR(10), Date, 101)

和第二个 Loser 子句:

SELECT
    CONVERT(VARCHAR(10), Date, 101) as Date,
    COUNT(*) as LoserCount
FROM
    table t1
WHERE
    t1.Result = 'Loser'
GROUP BY
     CONVERT(VARCHAR(10), Date, 101)

我想要实现的是获得这样的结果集:

Date       |    WinnerCount    | LoserCount
01/01/2017       24                  16
17/02/2017       13                  9

我尝试将此与join合并为两个结果集:

SELECT
    FirstSet.Date
FROM 
    (SELECT
         CONVERT(VARCHAR(10), Date, 101) as Date,
         COUNT(*) as Count
     FROM
         table t1
     WHERE
         t1.Result = 'Winner'
     GROUP BY
         CONVERT(VARCHAR(10), Date, 101)) AS FirstSet
JOIN
    (SELECT
         CONVERT(VARCHAR(10), Date, 101) as Date,
         COUNT(*) as Count
     FROM
         table t1
     WHERE
         t1.Result = 'Loser'
     GROUP BY
         CONVERT(VARCHAR(10), Date, 101)) AS SecondSet ON FirstSet.Date = SecondSet.Date
ORDER BY 
    FirstSet.Date

但在结果中我只得到了日期:/

3 个答案:

答案 0 :(得分:4)

您可以使用此查询。如果计算了所有行,您可以将所有必需文本的出现(* Winner"或"失败者"在这种情况下)。

SELECT
    CONVERT(VARCHAR(10), Date, 101) as Date,
    SUM(CASE WHEN t1.Result = 'Winner' THEN 1 ELSE 0 END) as WinnerCount,
    SUM(CASE WHEN t1.Result = 'Loser' THEN 1 ELSE 0 END) as LoserCount
from table t1
where t1.Result in ( 'Winner', 'Loser')
group by
    CONVERT(VARCHAR(10), Date, 101)

答案 1 :(得分:3)

以上接受的答案将为您提供正确的结果,但是如果您想保留计数而不使用Sum汇总结果,那么您也可以使用以下内容:

select
    CONVERT(VARCHAR(10), Date, 101) as Date,
    COUNT(CASE WHEN t1.Result = 'Winner' THEN 1 ELSE NULL END) as WinnerCount,
    COUNT(CASE WHEN t1.Result = 'Loser' THEN 1 ELSE NULL END) as LoserCount
from table as t1
where t1.Result in ('Winner', 'Loser')
group by 
    CONVERT(VARCHAR(10), Date, 101)

答案 2 :(得分:2)

您可以尝试以下内容:

dir1/dir2/dir3