求和(或计数)多个案例陈述

时间:2017-05-26 17:18:03

标签: sql sum case

我有下表:

Month | Item | Events | Party | Spirit | Faith |
May | 123 | 1 | 1 | 0 | 0 |
June |123 | 1 | 0 | 1 | 1 |

它基本上是1表示是0表示否。我需要知道每个项目每个月有多少不同的类别

我需要以下结果:

Month | Item | Counts |
May | 123 | 2 |
June| 123 | 3 |

这不起作用:

select Month, Item,
       sum(case when EVENTS = 1 then 1 when PARTY = 1 then 1 when SPIRIT = 1 then 1 when FAITH = 1 then 1 else 0 end) as Counts
from TABLE
group by 1,2

请帮助,谢谢!

2 个答案:

答案 0 :(得分:2)

您不需要汇总:

private static string caesar(string input, int n)
{
    //  Emrah Süngü's answer makes this part nicer, though it won't 
    //  make any difference at runtime. 
    input = input.Replace("Ä", "Ae");
    input = input.Replace("Ü", "Ue");
    input = input.Replace("Ö", "Oo");
    input = input.Replace("ß", "ss");
    input = input.Replace("ä", "ae");
    input = input.Replace("ü", "ue");
    input = input.Replace("ö", "oe");

    n = n % 94;

    StringBuilder cipher = new StringBuilder();

    for (int i = 0; i < input.Length; i++)
    {
        int code = ((int)input[i]);

        if (code >= 33 && code <= (126 - n))
        {
            code = code + n;
            char crypt = Convert.ToChar(code);
            cipher.Append(crypt);
        }
        else if (code > (126 - n) && code <= 126)
        {
            code = ((code + n) % 94);
            char crypt = Convert.ToChar(code);
            cipher.Append(crypt);
        }
        else
        {
            cipher.Append(input[i]);
        }

    }

    return cipher.ToString();
}

答案 1 :(得分:0)

CREATE TABLE #T
(
Month varchar(10), Item int, Events bit, Party bit, Spirit bit , Faith bit
)
insert into #T
SELECT 'May' , 123 , 1 , 1 , 0 , 0  union
SELECT 'June' ,123 , 1 , 0 , 1 , 1 

select Month, Item, CAST(Events AS INT) + CAST(Party AS INT)+ CAST(Spirit AS 
INT) +CAST(Faith AS INT)  from #T 

不需要聚合。由于事件,派对,精神和信仰都是位列,我们需要将其转换为int然后添加它。