2010-11-24 29 views
2

轉換行我都有以下結構列

Emp PayDate  Amount  
1 11/23/2010 500  
1 11/25/2010 -900  
1 11/28/2010 1000  
1 11/29/2010 2000  
2 11/25/2010 2000  
3 11/28/2010 -3000  
2 11/28/2010 4000  
3 11/29/2010 -5000 

我需要得到下面的結果,如果EMP 1選擇(前3日期及其相應的瓦爾斯 - 如果有的話 - 第4行總是被忽略)

PayDate1  Amount1 Paydate2  Amount2 Paydate3 Amount3 
11/23/2010 500  11/25/2010 -900  11/28/2010 1000 

我需要得到下面的結果,如果選擇了EMP 2

Paydate1 Amount1 Paydate2  Amount2 Paydate3 Amount3 
11/25/2010 2000  11/28/2010 4000  NULL  NULL 

我需要得到以下的結果,如果EMP 3選擇

Paydate1  Amount1 Paydate2  Amount2 Paydate3 Amount3 
11/28/2010 -3000  11/29/2010 -5000 

要獲得我可以運行下面的查詢行相應的數據:

select top 3 Paydate, Amount from Table where Emp = @Emp 

但我怎麼在一個轉動的方式獲得結果呢?

回答

0
CREATE TABLE dbo.Table1 
(
    Emp  int, 
    PayDate datetime, 
    Amount  int 
) 
GO 

INSERT INTO dbo.Table1 VALUES (1, '11/23/2010',500) 
INSERT INTO dbo.Table1 VALUES (1, '11/25/2010',-900) 
INSERT INTO dbo.Table1 VALUES (1, '11/28/2010',1000) 
INSERT INTO dbo.Table1 VALUES (1, '11/29/2010',2000) 
INSERT INTO dbo.Table1 VALUES (2, '11/25/2010',2000) 
INSERT INTO dbo.Table1 VALUES (3, '11/28/2010',-3000) 
INSERT INTO dbo.Table1 VALUES (2, '11/28/2010',4000) 
INSERT INTO dbo.Table1 VALUES (3, '11/29/2010',-5000) 


;WITH cte AS 
(SELECT Emp, PayDate, Amount, PayDateRowNumber 
FROM 
(SELECT Emp, 
     PayDate, 
     Amount, 
     ROW_NUMBER() OVER (PARTITION BY Emp ORDER BY PayDate) AS PayDateRowNumber 
FROM Table1) AS RankedTable1 
WHERE PayDateRowNumber < 4) 
SELECT c1.Emp AS Emp, c1.PayDate AS PayDate1 
     ,c1.Amount AS Amount1, c2.PayDate AS PayDate2 
     ,c2.Amount AS Amount2, c3.PayDate AS PayDate3, c3.Amount AS Amount3 
FROM cte c1 
LEFT JOIN cte c2 ON c2.Emp = c1.Emp AND c2.PayDateRowNumber = 2 
LEFT JOIN cte c3 ON c3.Emp = c2.Emp AND c3.PayDateRowNumber = 3 
WHERE c1.PayDateRowNumber = 1 

輸出是:

alt text

一些注意事項是,它不會總金額爲同一僱主/日期(儘管可以很容易地改變)。也可能需要更改以查看ROW_NUMBER()與RANK()和DENSE_RANK()的使用情況,具體取決於您對「TOP 3」的定義

1

有在樞軸上的優秀文章與SQL Server 2005+ here