将数据拆分为SQL中的列

时间:2014-04-21 11:54:18

标签: sql sql-server

我有一张包含以下数据的表

Date            Value
---------------------
2014-01-01        20
2014-01-02        18
2014-01-03        06
2014-02-01        22
2014-02-02        162
2014-02-03        16

这里我有2个月的前3个日期数据。我得到了输出

Date  Jan 2014  Feb 2014
-------------------------
 01    20          06
 02    18          162
 03    06          16

2 个答案:

答案 0 :(得分:1)

测试数据

DECLARE @TABLE TABLE([Date] DATE,Value INT)
INSERT INTO @TABLE VALUES
('2014-01-01',20)  ,('2014-01-02',18),
('2014-01-03',06)  ,('2014-02-01',22),
('2014-02-02',162) ,('2014-02-03',16)

<强>查询

SELECT * FROM (
SELECT DAY([Date]) AS [Date]
      ,LEFT(DATENAME(MONTH,[Date]), 3)
       + ' ' + CAST(YEAR([Date]) AS NVARCHAR(4)) Mon_YYYY
      , Value
FROM @TABLE ) t
PIVOT (SUM(Value)
       FOR Mon_YYYY
       IN ([Jan 2014],[Feb 2014])
       )P

结果集

╔══════╦══════════╦══════════╗
║ Date ║ Jan 2014 ║ Feb 2014 ║
╠══════╬══════════╬══════════╣
║    1 ║       20 ║       22 ║
║    2 ║       18 ║      162 ║
║    3 ║        6 ║       16 ║
╚══════╩══════════╩══════════╝

您需要使用Dynamic sql来取消实际数据,因为列中可能有很多值,而且这个解决方案对于现实生活中的问题并不实用,但至少它可以让您了解如何去实现它。请参阅此How to pivot unknown number of columns & no aggregate in SQL Server?以了解如何动态转动行。

答案 1 :(得分:0)

您可以使用PIVOT,如下所示

declare @t table (sdate date,val int)
insert into @t values('2014-01-01',        20)
insert into @t values('2014-01-02',        18)
insert into @t values('2014-01-03',        06)
insert into @t values('2014-02-01',        22)
insert into @t values('2014-02-02',        162)
insert into @t values('2014-02-03',        16)

select * from 
(
select datepart(d,sdate) sday,DATENAME(MONTH, sdate)+' '+cast(datepart(YYYY,sdate) as varchar) yearMonth,val from @t
) t
pivot 
(
sum(val)
FOR YearMonth IN ([January 2014],[February 2014])
) AS PivotTable;

这是结果

sday January 2014 February 2014
1        20       22
2        18       162
3        6        16