用于归因建模的SQL透视

时间:2016-03-14 10:33:36

标签: sql sql-server pivot

我正在努力转换一些如下所示的SQL数据:(此表称为[OGtable]

   Date            SiteKey UserKey ConversionNo Ranking    Type      TimeDiff
18/01/2016 19:51    eBay      a     1             1     Impression     NULL
18/01/2016 19:55    eBay      a     1             2     Impression       0
19/01/2016 20:26    eBay      a     1             3     Conversion     1475

我的目标是将其变成这样的东西:

SiteKey UserKey ConversionNo    Type    TimeDiff    Path                   CaseNumber
eBay      a        1         Impression    0      Impression1,Impression2   1testaa
eBay      a        1         Conversion   1475    Impression2,Conversion    1testaa

我尝试过旋转,但我只改变了整个用户路径,即:

  CaseNumber                              Path
1test1000204837065964386a   Impression1.Impression2.Z_Conversion3

那么请任何人帮我正确实现枢轴功能(或通过其他方式实现这一点吗?)

非常感谢!

威尔

我的失败脚本如下:

SELECT DISTINCT casekey, (
    SELECT REPLACE(LTRIM(STUFF(
    (
        SELECT DISTINCT '.' + CONCAT(inq.Type,inq.Ranking)
        FROM (
            SELECT 
                Ranking,
                CONCAT(ConversionNo,'test',UserKey,'a') AS casekey,
                CASE WHEN EventTypeKey in (4) THEN 'Z_Conversion' ELSE 'Impression' END AS Type
            FROM #OGtable
            GROUP BY
                Ranking,
                CONCAT(ConversionNo,'test',UserKey,'a'),
                CASE WHEN Type in ('Conversion') THEN 'Z_Conversion' ELSE 'Impression' END 
        ) inq
        WHERE inq.casekey = outq.casekey FOR XML PATH('')
    ), 1, 1, '')), '&', '&')) AS Nodes
FROM (
    SELECT
        CONCAT(ConversionNo,'test',UserKey,'a') AS casekey,
        CASE WHEN Type in ('Impression') THEN 'Impression' ELSE 'Conversion' END AS Type
    FROM #OGtable 
) outq

0 个答案:

没有答案