2016-07-06 54 views
2

我有以下查詢:在SQL Server中添加列支點查詢

select 
    msisdn, value, date 
from 
    tang 
where 
    date > dateadd(mm, -6, getdate()) 
    and value > 0 

有了這樣一些數據:

msisdn  value date 
772102730 1.0000 2016-01-07 08:48:30.540 
772125566 2.0000 2016-01-07 10:01:50.753 
772108924 1.0000 2016-01-07 10:04:27.940 
772136349 5.0000 2016-01-07 10:08:07.183 
772127823 1.0000 2016-01-07 10:08:19.773 
774521923 1.0000 2016-01-07 10:10:13.927 

和下面轉動查詢:

select msisdn,r1,r2,r3 
from 
(
    select * 
    from 
    (
     select msisdn, value, 'r'+convert(varchar(4),rank() over (partition by msisdn order by date asc)) as r 
     from tang 
     where date > dateadd(mm,-6,getdate()) 
     and value > 0 
    ) a 
    where r < 'r4' 
) a 
pivot 
(
     min(value) 
     for r in (r1,r2,r3) 
) p 

與以下數據:

msisdn  r1  r2  r3 
701048594 1.0000 2.0000 2.0000 
720000810 2.0000 NULL NULL 
720030474 2.0000 2.0000 NULL 
720049121 4.5000 2.0000 3.0000 
720187431 2.0000 2.0000 2.0000 
720189845 3.0000 NULL NULL 
720201300 5.0000 NULL NULL 
720229335 2.0000 NULL NULL 
720458626 2.0000 2.0000 2.0000 
720512511 2.0000 5.0000 2.5000 

,我想數據的列添加如下:

msisdn r1 r2 r3 d1 d2 d3 

其中d1爲R1的數據,D2是R2和D3的數據是R3

的數據如何做到這一點?

+0

你是什麼意思'd1是r1'等的數據?你的意思是日期欄中的值嗎? – Taryn

+0

pivot數據庫的mssql實現非常有限。我建議你回到使用基於rank和group by子句的派生表和case表達式。 '最大(當r = 1,然後列結束時)' –

+0

對於混淆感到抱歉,數據意味着r1的日期等,請參閱第一個表格。 – sorineatza

回答

0

我已經解決了這個問題,下面的查詢:
select a.msisdn, r1, r2, r3, r1_date, r2_date, r3_date from ( select msisdn,r1,r2,r3 from ( select * from ( select msisdn, value, ''r''+convert(varchar(4),rank() over (partition by msisdn order by date asc)) as r from tang where date > dateadd(mm,-6,getdate()) and value > 0) a where r < ''r4'') a pivot ( min(value) for r in (r1,r2,r3) ) p) a join ( select msisdn,r1_date,r2_date,r3_date from ( select * from ( select msisdn, date, ''r''+convert(varchar(4),rank() over (partition by msisdn order by date asc))+''_date'' as r from tang where date > dateadd(mm,-6,getdate()) and value > 0) a where r < ''r4_date'') a pivot ( min(date) for r in (r1_date,r2_date,r3_date) ) p) b on a.msisdn = b.msisdn

0

您可以使用此查詢,而不是合併2個樞查詢獲得更好的性能。

SELECT msisdn, 
     MIN(CASE WHEN r = 1 THEN value END) AS r1, 
     MIN(CASE WHEN r = 2 THEN value END) AS r2, 
     MIN(CASE WHEN r = 3 THEN value END) AS r3, 
     MIN(CASE WHEN r = 4 THEN value END) AS r4, 
     MIN(CASE WHEN r = 1 THEN date END) AS d1, 
     MIN(CASE WHEN r = 2 THEN date END) AS d2, 
     MIN(CASE WHEN r = 3 THEN date END) AS d3, 
     MIN(CASE WHEN r = 4 THEN date END) AS d4 
FROM (SELECT msisdn, 
       value, 
       RANK() OVER (PARTITION BY msisdn ORDER BY date ASC) AS r 
     FROM tang 
     WHERE date > DATEADD(mm,-6,GETDATE()) 
       AND value > 0 
     ) a 
WHERE r < 4 
GROUP BY msisdn