需要选择查询才能获得如下所示的输出。

时间:2017-01-12 11:12:14

标签: sql asp.net sql-server

我有一个SQL表,如下所示,

| Loc | Date | Id | Sts |
-------------------------
|   Hyd |   15-01-2016  |   1   |   A   |

|   Vjd |   16-01-2016  |   2   |   B   |

|   Viz |   15-01-2016  |   3   |   C   |

|   Hyd |   15-03-2016  |   4   |   A   |

|   Vjd |   15-03-2016  |   5   |   B   |

|   Viz |   15-03-2016  |   6   |   C   |

|   Hyd |   15-03-2016  |   4   |   A   |

|   Vjd |   15-05-2016  |   5   |   B   |

|   Viz |   15-05-2016  |   6   |   C   |

我需要输出,

**| Loc | Jan-16    |   Mar-16  |   May-16  |**  
**|-------|A |B |C |A |B |C |A |B |C |**  

----------
|Hyd | 1 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 |    
|Vjd | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 1 | 0 |  
|Viz | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 1 |  

任何人都可以帮帮我..

先谢谢。

1 个答案:

答案 0 :(得分:2)

您基本上需要根据CASE语句进行聚合,如下所示:

DECLARE @table TABLE (loc VARCHAR(3), [date] DATE, id INT, sts CHAR(1));
INSERT INTO @table SELECT 'Hyd', '20160115', 1, 'A';
INSERT INTO @table SELECT 'Vjd', '20160116', 2, 'B';
INSERT INTO @table SELECT 'Viz', '20160115', 3, 'C';
INSERT INTO @table SELECT 'Hyd', '20160315', 4, 'A';
INSERT INTO @table SELECT 'Vjd', '20160315', 5, 'B';
INSERT INTO @table SELECT 'Viz', '20160315', 6, 'C';
INSERT INTO @table SELECT 'Hyd', '20160315', 4, 'A';
INSERT INTO @table SELECT 'Vjd', '20160515', 5, 'B';
INSERT INTO @table SELECT 'Viz', '20160515', 6, 'C';

SELECT
    loc,
    COUNT(CASE WHEN YEAR([date]) = 2016 AND MONTH([date]) = 1 AND sts = 'A' THEN 1 END) AS Jan_A,
    COUNT(CASE WHEN YEAR([date]) = 2016 AND MONTH([date]) = 1 AND sts = 'B' THEN 1 END) AS Jan_B,
    COUNT(CASE WHEN YEAR([date]) = 2016 AND MONTH([date]) = 1 AND sts = 'C' THEN 1 END) AS Jan_C,
    COUNT(CASE WHEN YEAR([date]) = 2016 AND MONTH([date]) = 3 AND sts = 'A' THEN 1 END) AS Mar_A,
    COUNT(CASE WHEN YEAR([date]) = 2016 AND MONTH([date]) = 3 AND sts = 'B' THEN 1 END) AS Mar_B,
    COUNT(CASE WHEN YEAR([date]) = 2016 AND MONTH([date]) = 3 AND sts = 'C' THEN 1 END) AS Mar_C,
    COUNT(CASE WHEN YEAR([date]) = 2016 AND MONTH([date]) = 5 AND sts = 'A' THEN 1 END) AS May_A,
    COUNT(CASE WHEN YEAR([date]) = 2016 AND MONTH([date]) = 5 AND sts = 'B' THEN 1 END) AS May_B,
    COUNT(CASE WHEN YEAR([date]) = 2016 AND MONTH([date]) = 5 AND sts = 'C' THEN 1 END) AS May_C
FROM
    @table
GROUP BY
    loc;

结果:

loc Jan_A   Jan_B   Jan_C   Mar_A   Mar_B   Mar_C   May_A   May_B   May_C
Hyd     1       0       0       2       0       0       0       0       0
Viz     0       0       1       0       0       1       0       0       1
Vjd     0       1       0       0       1       0       0       1       0