2017-10-14 86 views
0

我想合併兩個非常相似的查詢。唯一不同的就是WHERE子句中:兩個不同的where子句的SQL Server查詢

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) 

,第二個具有失敗者條款:

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 

我試圖合併這與加入兩個結果集:

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 

但在結果中我只有日期:/

回答

4

您可以使用此查詢。計算所有行的insted的,你可以總計所需的文本的所有匹配(*贏家」或‘在這種情況下失敗者’)

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) 
2

你可以嘗試類似:

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

以上所接受的答案將爲您提供正確的結果,但是如果您想保留計數並且不使用總和來彙總結果,則可以使用以下選項:

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)