我的表有很多列,但只需要前两个
Mtype join_date Other
A 28/05/2014 00:00 xx
B 04/11/2014 00:00 xx
C 23/03/2007 00:00 xx
D 04/09/2013 00:00 xx
E 26/11/2014 00:00 xx
F 24/07/2011 00:00 xxx
G 28/05/2014 00:00 xx
A 20/06/2013 00:00 x
B 04/11/2014 00:00 x
C 20/06/2013 00:00 x
这是我想要的结果
+-------+---------+---------+---------+---------+---------+---------+--------+--------+--------+
| Mtype | 2015-03 | 2015-02 | 2015-01 | 2014-12 | 2014-11 | 2014-10 | 2014-9 | 2014-8 | 2014-7 |
+-------+---------+---------+---------+---------+---------+---------+--------+--------+--------+
| A | 45 | 7 | 54 | 875 | 45 | 7 | 54 | 875 | 25 |
| B | 7 | 78 | 78 | 7 | 7 | 78 | 78 | 7 | 78 |
| C | 546 | 6 | 87 | 5 | 45 | 6 | 87 | 5 | 25 |
| D | 54 | 78 | 54 | 8 | 54 | 78 | 54 | 7 | 7 |
| E | 78 | 78 | 7 | 45 | 78 | 78 | 7 | 45 | 6 |
| F | 46 | 54 | 6 | 8 | 46 | 54 | 6 | 8 | 75 |
| G | 54 | 87 | 87 | 7 | 54 | 87 | 87 | 45 | 8 |
+-------+---------+---------+---------+---------+---------+---------+--------+--------+--------+
代码
DECLARE @cols NVARCHAR (MAX)
DECLARE @query NVARCHAR (MAX)
SELECT @cols = COALESCE (@cols + ',[' + CONVERT(VARCHAR(7), join_date, 120) + ']',
'[' + CONVERT(VARCHAR(7), join_date, 120) + ']')
FROM (SELECT DISTINCT CONVERT(VARCHAR(7), join_date, 120) as join_date FROM MD T0) PV
ORDER BY join_date DESC
SELECT @query = 'SELECT *
FROM
(
SELECT Mtype, CONVERT(VARCHAR(7), join_date, 120) as join_date FROM MD T0
) AS t
PIVOT
(
COUNT(join_date)
FOR join_date IN( ' + @cols + ')' +
') AS p ;'
EXEC SP_EXECUTESQL @query
我遇到的问题是我只看到三列Mtype,(日期),(日期)取决于
ORDER BY join_date DESC
+-------+---------+---------+
| Mtype | 2015-09 | 2015-08 |
+-------+---------+---------+-
| A | 45 | 7 |
| B | 7 | 78 |
| C | 546 | 6 |
| D | 54 | 78 |
| E | 78 | 78 |
| F | 46 | 54 |
| G | 54 | 87 |
+-------+---------+---------+
这两列是DESC 2015-09和2015-08或ASC 1989-07和1990-05。 我的问题是我的查询有什么问题,我只看到2个日期列而不是所有列(超过100个)。
答案 0 :(得分:0)
如果你运行它会怎么样?
DECLARE @cols NVARCHAR (MAX)
DECLARE @query NVARCHAR (MAX)
CREATE TABLE #VALS (VALS NVARCHAR(4000))
INSERT INTO #VALS
SELECT DISTINCT CONVERT(VARCHAR(7), join_date, 120)
FROM MD T0
ORDER BY CONVERT(VARCHAR(7), join_date, 120)
SELECT @COLS = COALESCE(@COLS+', ','') + '[' + VALS + ']' FROM #VALS
SET @QUERY = '
;WITH CTE AS (
SELECT MTYPE, CONVERT(VARCHAR(7), join_date, 120) AS join_date, COUNT(*) AS RECORDS
FROM MD T0)
SELECT *
FROM CTE
PIVOT(SUM(RECORDS) FOR join_date IN ('+@cols+')) PIV'
EXEC SP_EXECUTESQL @query