2014-11-02 2 views
0

매우 큰 테이블 151 열이 있습니다. 각 열은 하나의 저장소 (150 개 저장소 * 1 열)와 하나의 날짜 열을 나타냅니다. 다음과 같이 Sql 열에서 행으로 변환하는 쿼리

Date   Store001  Store002  Store003  Store004 ................... Store150 
---------------------------------------------------------------------------------------------------  
01/01/14  12560   8546   7468   10154      16845 

31/10/14  13978   7584   8456   13458      25458 

나는 결과를 필요

Date   Store#  Amount 
----------------------------------- 
01/01/14  Store001  12560 
01/01/14  Store002  8546 
01/01/14  Store003  7468 
01/01/14  Store004  10154 
etc., 
+0

[열 이름 피벗 해제]의 내 대답 –

+0

중복 가능성을 확인 (http://stackoverflow.com/questions/19055902/unpivot-with-column-name) –

답변

0
Create table yourtable([Date] date,Store001 int ,Store002 int) 
insert into yourtable ([Date],Store001,Store002) 
values 
(GETDATE(),1243,546), 
(GETDATE(),4545,798), 
(GETDATE(),5687,456), 
(GETDATE(),0756,685) 

간단한 쿼리

;WITH CTE 
AS 
    (
    SELECT * FROM (
    SELECT [Date],Store001,Store002 FROM yourtable) T 
    UNPIVOT (Value FOR N IN (Store001,Store002))P 
) 
SELECT [Date],N as Store#,SUM(Value) as Amount 
FROM CTE 
GROUP BY [Date],N 

동적 SQL

,
declare @cols nvarchar(max) 
select @cols = coalesce(@cols+N',', N'') + quotename(c.name) from syscolumns c 
inner join sysobjects o on c.id = o.id and o.xtype = 'u' 
where o.name = 'yourtable' and c.name not in ('Date') order by c.colid 
select @cols 
declare @query nvarchar(max) 

select @query = N' 
;WITH CTE 
AS 
    (
    SELECT * FROM (
    SELECT [Date], ' + @cols + ' 
FROM yourtable) T 
    UNPIVOT (Value FOR N IN (' + @cols + '))P 
) 
SELECT [Date],N as Store#,SUM(Value) as Amount 
FROM CTE 
GROUP BY [Date],N 
' 
print @query 
exec sp_executesql @query 

OUTPUT이

Date   Store#  Amount 
2014-11-02 Store001 12231 
2014-11-02 Store002 2485 
+0

우수 Ganesh 씨. 방금 등록했기 때문에 빠른 응답을 기대하지 않았습니다. –

+0

@MohanYGK 도움이된다고 생각하시면 환영합니다 –

+0

생산, 재고, 소매 관리, 급여, 재무 등 150 개 소매점을 대상으로 AX 2012를 구현하고 있습니다. 저는 IT 관리자 직책을 찾고 있습니다. 회사. 나는 배경과 관심사를 모르지만 관심이 있다면 알려주지. –

관련 문제