如何在 sql 中创建动态列?
how to create dynamics columns in sql?
有一个 table,日期列格式为数字 (20150101)。我如何计算每个月有多少天,并在新的临时 table 中创建月份作为列。例如,如果我有:
Date
20150101
20150102
20150201
20150302
20150304
我愿意return
Jan Feb Mar
2 1 2
谢谢
试试这个:
DECLARE @t TABLE ( d INT )
INSERT INTO @t
VALUES ( 20150101 ),
( 20150102 ),
( 20150201 ),
( 20150302 ),
( 20150304 );
WITH cte
AS ( SELECT LEFT(DATENAME(mm,
( CAST(CAST(d AS NVARCHAR(8)) AS DATE) )),
3) AS m ,
COUNT(*) AS c
FROM @t
GROUP BY LEFT(DATENAME(mm,
( CAST(CAST(d AS NVARCHAR(8)) AS DATE) )),
3)
)
SELECT *
FROM cte PIVOT ( MAX(c) FOR m IN ( [Jan], [Feb], [Mar], [Apr], [May],
[Jun], [Jul], [Aug], [Sep], [Oct],
[Nov], [Dec] ) ) AS p
输出:
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
2 1 2 NULL NULL NULL NULL NULL NULL NULL NULL NULL
只计算不同的日期:
DECLARE @t TABLE ( d INT )
INSERT INTO @t
VALUES ( 20150101 ),
( 20150101 ),
( 20150102 ),
( 20150201 ),
( 20150302 ),
( 20150304 );
WITH cte
AS ( SELECT LEFT(DATENAME(mm,
( CAST(CAST(d AS NVARCHAR(8)) AS DATE) )),
3) AS m ,
COUNT(*) AS c
FROM (SELECT DISTINCT * FROM @t) t
GROUP BY LEFT(DATENAME(mm,
( CAST(CAST(d AS NVARCHAR(8)) AS DATE) )),
3)
)
SELECT *
FROM cte PIVOT ( MAX(c) FOR m IN ( [Jan], [Feb], [Mar], [Apr], [May],
[Jun], [Jul], [Aug], [Sep], [Oct],
[Nov], [Dec] ) ) AS p
有一个 table,日期列格式为数字 (20150101)。我如何计算每个月有多少天,并在新的临时 table 中创建月份作为列。例如,如果我有:
Date
20150101
20150102
20150201
20150302
20150304
我愿意return
Jan Feb Mar
2 1 2
谢谢
试试这个:
DECLARE @t TABLE ( d INT )
INSERT INTO @t
VALUES ( 20150101 ),
( 20150102 ),
( 20150201 ),
( 20150302 ),
( 20150304 );
WITH cte
AS ( SELECT LEFT(DATENAME(mm,
( CAST(CAST(d AS NVARCHAR(8)) AS DATE) )),
3) AS m ,
COUNT(*) AS c
FROM @t
GROUP BY LEFT(DATENAME(mm,
( CAST(CAST(d AS NVARCHAR(8)) AS DATE) )),
3)
)
SELECT *
FROM cte PIVOT ( MAX(c) FOR m IN ( [Jan], [Feb], [Mar], [Apr], [May],
[Jun], [Jul], [Aug], [Sep], [Oct],
[Nov], [Dec] ) ) AS p
输出:
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
2 1 2 NULL NULL NULL NULL NULL NULL NULL NULL NULL
只计算不同的日期:
DECLARE @t TABLE ( d INT )
INSERT INTO @t
VALUES ( 20150101 ),
( 20150101 ),
( 20150102 ),
( 20150201 ),
( 20150302 ),
( 20150304 );
WITH cte
AS ( SELECT LEFT(DATENAME(mm,
( CAST(CAST(d AS NVARCHAR(8)) AS DATE) )),
3) AS m ,
COUNT(*) AS c
FROM (SELECT DISTINCT * FROM @t) t
GROUP BY LEFT(DATENAME(mm,
( CAST(CAST(d AS NVARCHAR(8)) AS DATE) )),
3)
)
SELECT *
FROM cte PIVOT ( MAX(c) FOR m IN ( [Jan], [Feb], [Mar], [Apr], [May],
[Jun], [Jul], [Aug], [Sep], [Oct],
[Nov], [Dec] ) ) AS p