2017-08-29 59 views
1

我有一個表SQL樞不處理數據缺失

Create table dbo.temp(ID int, ExpenseID int, ExpenseName Varchar(100) null, ExpenseDate date null, Value decimal(19,4) null) 
    Insert into dbo.temp values(1,100,'CostClothes','2015-01-01',100.0000) 
    Insert into dbo.temp values(1,200,'Discount','2015-01-01',1.0000) 

    Insert into dbo.temp values(2,100,'CostClothes','2016-01-01',250.0000) 
    Insert into dbo.temp values(2,200,'Discount','2016-01-01',1.0000) 

    Insert into dbo.temp values(1,100,'CostClothes','2014-01-01',500.0000) 
    Insert into dbo.temp values(2,200,'Discount','2014-01-01',5.0000) 

現在我想轉動的ExpenseID和預期輸出此表的是

Create table dbo.output(ID int, CostClothes decimal(19,4) null, Discount decimal(19,4) null, ExpenseDate date null) 
    insert into dbo.output values (1,100.0000,1.0000,'2015-01-01') 
    insert into dbo.output values (1,500.0000,NULL,'2014-01-01') 
    insert into dbo.output values (2,NULL,5.0000,'2014-01-01') 
    insert into dbo.output values (2,100.0000,1.0000,'2016-01-01') 

這是我有什麼,我沒有得到正確的輸出

SELECT ID,ISNULL([100],0) as CostClothes,ISNULL([200],0) as Discount,expenseDate 
    FROM 
    (
    SELECT * FROM dbo.temp 
) AS p 
    PIVOT 
    (
    MAX(Value) for ExpenseID in ([100],[200]) 
) AS PV1 

如何更改查詢

謝謝 MR

回答

1

給定樣本數據,您可以使用聚合或只是一個簡單的條件聚合進行數據透視。

select 
    ID 
    ,max(case when ExpenseName = 'CostClothes' then Value end) as CostClothes 
    ,max(case when ExpenseName = 'Discount' then Value end) as Discount 
    ,ExpenseDate 
from 
    dbo.temp 
group by 
    ID 
    ,ExpenseDate 
order by 
    ID 

透視法

select 
    ID 
    ,CostClothes = max(CostClothes) 
    ,Discount = max(Discount) 
    ,ExpenseDate 
from 
    dbo.temp 
pivot(
    max(Value) for ExpenseName in (CostClothes, Discount) 
) p 
group by 
    ID 
    ,ExpenseDate 
order by 
    ID 

演示:http://rextester.com/ENHTIK13664

0

你的問題是,你選擇在派生表太多的信息。

如果你打算使用Select *,你甚至不需要派生表。當使用PIVOT時,您應該只選擇最終結果中需要的字段。與編寫條件聚合查詢的方式相同。

SELECT ID, 
     ISNULL([100], 0) AS CostClothes, 
     ISNULL([200], 0) AS Discount, 
     expenseDate 
FROM 
(
    SELECT ID, 
      ExpenseID, 
      ExpenseDate, 
      Value 
    FROM temp 
) AS p PIVOT(MAX(Value) FOR ExpenseID IN([100],[200])) AS PV1 

這應該通過消除ExpenseName列給你想要的結果。或者您可以使用ExpenseName列並刪除ExpenseID