T SQL Count问题

时间:2010-03-18 00:42:08

标签: sql-server-2005 tsql

我正在制作一份报告,其中包含5列,其中包含v1aa,v1ab和v1ac。

我想要做的是计算5列中的所有v1aa并显示结果(对于v1ab和v1ac也是如此)

我喜欢如何显示的示例如下: -

Amber = 3 (v1aa code)
Blue =  2 (v1ab code)
Red  = 1 (v1ac code)

有人可以给我任何建议让我入门吗?

4 个答案:

答案 0 :(得分:1)

我需要确定数据,但听起来像是cross tab query

答案 1 :(得分:0)

这是你要找的吗?

SELECT
    SUM((CASE WHEN Column1 = 'v1aa' THEN 1 ELSE 0 END)
        + (CASE WHEN Column2 = 'v1aa' THEN 1 ELSE 0 END)
        + (CASE WHEN Column3 = 'v1aa' THEN 1 ELSE 0 END)
        + (CASE WHEN Column4 = 'v1aa' THEN 1 ELSE 0 END)
        + (CASE WHEN Column5 = 'v1aa' THEN 1 ELSE 0 END))
    AS Amber,
    SUM((CASE WHEN Column1 = 'v1ab' THEN 1 ELSE 0 END)
        + (CASE WHEN Column2 = 'v1ab' THEN 1 ELSE 0 END)
        + (CASE WHEN Column3 = 'v1ab' THEN 1 ELSE 0 END)
        + (CASE WHEN Column4 = 'v1ab' THEN 1 ELSE 0 END)
        + (CASE WHEN Column5 = 'v1ab' THEN 1 ELSE 0 END))
    AS Blue,
    SUM((CASE WHEN Column1 = 'v1ac' THEN 1 ELSE 0 END)
        + (CASE WHEN Column2 = 'v1ac' THEN 1 ELSE 0 END)
        + (CASE WHEN Column3 = 'v1ac' THEN 1 ELSE 0 END)
        + (CASE WHEN Column4 = 'v1ac' THEN 1 ELSE 0 END)
        + (CASE WHEN Column5 = 'v1ac' THEN 1 ELSE 0 END))
    AS Red
FROM
    dbo.MyTable

答案 2 :(得分:0)

我认为这会让你开始。如果可能为NULL,则可能需要添加WHERE子句,或者在您不希望在报表中显示的数据中添加其他代码。

SELECT CASE i.code
    WHEN 'v1aa' THEN 'Amber'
    WHEN 'v1ab' THEN 'Blue'
    WHEN 'v1ac' THEN 'Red' END,
    COUNT(*)
FROM
(
    SELECT Col1 AS Code FROM Test
    UNION ALL SELECT Col2 FROM Test
    UNION ALL SELECT Col3 FROM Test
    UNION ALL SELECT Col4 FROM Test
    UNION ALL SELECT Col5 FROM Test
) i
GROUP BY i.Code

答案 3 :(得分:0)

如果您希望每条记录都有这些计数,请尝试:

Select
    Case When Col1 Like '%v1aa%' Then 1 Else 0 End +
    Case When Col2 Like '%v1aa%' Then 1 Else 0 End +
    Case When Col3 Like '%v1aa%' Then 1 Else 0 End +
    Case When Col4 Like '%v1aa%' Then 1 Else 0 End +
    Case When Col5 Like '%v1aa%' Then 1 Else 0 End As AmberCount,
    Case When Col1 Like '%v1ab%' Then 1 Else 0 End +
    Case When Col2 Like '%v1ab%' Then 1 Else 0 End +
    Case When Col3 Like '%v1ab%' Then 1 Else 0 End +
    Case When Col4 Like '%v1ab%' Then 1 Else 0 End +
    Case When Col5 Like '%v1ab%' Then 1 Else 0 End As BlueCount,
    Case When Col1 Like '%v1ac%' Then 1 Else 0 End +
    Case When Col2 Like '%v1ac%' Then 1 Else 0 End +
    Case When Col3 Like '%v1ac%' Then 1 Else 0 End +
    Case When Col4 Like '%v1ac%' Then 1 Else 0 End +
    Case When Col5 Like '%v1ac%' Then 1 Else 0 End As RedCount
From MyTable

如果你想要整个表的计数,那么添加一个Sum()聚合函数,正如Timothy Khouri在他的回答中所建议的那样