2016-09-21 137 views
1
iItemKey Qty FreeQty Unit TaxCatKey TaxVal 
    7  1 1  1  1  4.00 
    7  1 1  1  1  1.00 

我需要輸出SQL查詢樞軸轉動爲值

iItemKey Qty FreeQty Unit TaxCatKey VAT A.VAt 
    7  1 1  1  1  4.00 1.00 

這裏是我的查詢。但我得到的增值稅和A.Vat值作爲空

WITH T 
    AS (SELECT  T_ItemRequestSub.iItemKey, T_ItemRequestSub.Qty, T_ItemRequestSub.FreeQty, T_ItemRequestSub.Unit, T_ItemRequestSub.TaxType, 
        M_Mt_TaxCategorySub.iTaxCatKey , M_Mt_TaxCategorySub.iTaxVal 
FROM   T_ItemRequestSub INNER JOIN 
         T_ItemRequest ON T_ItemRequestSub.iReqKey = T_ItemRequest.iKey INNER JOIN 
         M_Mt_TaxCategory ON T_ItemRequestSub.TaxType = M_Mt_TaxCategory.iKey INNER JOIN 
         M_Mt_TaxCategorySub ON M_Mt_TaxCategory.iKey = M_Mt_TaxCategorySub.iTaxCatKey where T_ItemRequestSub.iKey = 2) 
SELECT * 
FROM T PIVOT (sum (iTaxVal) FOR TaxType IN ( 
     [Vat], 
     [A.Vat] 
    )) AS pvt 

請幫助

+0

你能解釋一下輸出背後的邏輯? –

+0

如果您的輸入中有3行,該怎麼辦? – p2k

回答

0

唯一不同的值是TaxVal所以我懷疑你正在嘗試做以下:

WITH Src AS --Your source table 
(
    SELECT * FROM (VALUES 
    (7, 1, 1, 1, 1, 4.00), 
    (7, 1, 1, 1, 1, 1.00) 
    )T(iItemKey, Qty, FreeQty, Unit, TaxCatKey, TaxVal) 
) 
SELECT * FROM 
(
    SELECT iItemKey, Qty, FreeQty, Unit, TaxCatKey, TaxVal, CASE WHEN TaxVal = 1.00 THEN 'VAT' ELSE 'A.VAT' END Col 
    FROM Src 
) T 
PIVOT (MAX(TaxVal) FOR Col IN ([VAT], [A.VAT])) P 
+0

其工作亞爾 – Edburg