2010-04-23 143 views

回答

1

這有點凌亂,但它在這裏。所有的

首先,我使用的秩()函數來知道的位置(1,2或3)ErrorField的。所有這一切,我使用該數字爲樞軸。 你需要兩個樞軸和它們之間的連接。

WITH AuxTable (Data_Error_Key, ErrorField, ErrorValue, NumeroError) 
AS 
(
SELECT Data_Error_Key, ErrorField, ErrorValue, RANK() OVER (PARTITION BY Data_Error_Key ORDER BY Data_Error_Key, ErrorField) 
FROM dbo.TempTable 
) 
SELECT TablaErrorField.Data_Error_Key, ErrorField1, ErrorValue1,ErrorField2,ErrorValue2, ErrorField3, 
     ErrorValue3 
FROM 
(
    SELECT Data_Error_Key, [1] as ErrorField1, [2] as ErrorField2, [3] as ErrorField3 
    FROM (
    SELECT Data_Error_Key,NumeroError, ErrorField 
    FROM AuxTable) P 
    PIVOT 
    (
    MAX (ErrorField) 
    FOR NumeroError IN ([1], [2], [3]) 
    ) AS pvt) As TablaErrorField 
INNER JOIN 
(
    SELECT Data_Error_Key, [1] as ErrorValue1, [2] as ErrorValue2, [3] as ErrorValue3 
    FROM (
    SELECT Data_Error_Key,NumeroError, ErrorValue 
    FROM AuxTable) P 
    PIVOT 
    (
    MAX (ErrorValue) 
    FOR NumeroError IN ([1], [2], [3]) 
    ) AS pvt) as TablaErrorValue 
ON TablaErrorField.Data_Error_Key= TablaErrorValue.Data_Error_Key 

這一切都假設您只需要3對ErrorField/ErrorValue。否則,你應該看看我的回答this的問題。

1

我不知道,如果你能做到這一點與SQL Server PIVOT功能。該函數總是假設並需要某種數值的集合函數(COUNT,AVG) - 您不能僅將行轉換爲列。

在你的情況,如果你事先知道你的錯誤的字段,你可以做這樣的事情:

SELECT 
    ErrorKey, 
    [Field1] AS Field1, [Field2] AS Field2, [Field10] AS Field10, 
    [Field11] AS Field11, [Field13] as Field13, [Field14] as Field14, 
    [Field15] as Field15, [Field21] as field21 
FROM 
    (SELECT ErrorKey, ErrorField, ErrorValue 
    FROM Errors) e 
PIVOT 
(
COUNT (ErrorValue) 
FOR ErrorField IN 
    ([Field1], [Field2], [Field10], [Field11], [Field13], 
     [Field14], [Field15], [Field21]) 
) AS pvt 
ORDER BY pvt.ErrorKey 

這將產生一個輸出這樣的事情:

ErrorKey Field1 Field2 Field10 Field11 Field13 Field14 Field15 field21 
    1   1  1  1  0  0  0  0  0 
    2   0  0  0  1  1  1  0  0 
    3   0  0  0  0  0  0  1  1 

這將使你爲每個錯誤鍵在特定字段中的錯誤計數。