2013-12-24 61 views
0

我需要清理一些數據,方法是將兩個相似但略有不同的維度字段值合併到一個新行中,將兩個度量值相加,以保持uid和日期不變。如何將兩個不同的字段值合併到一行中?

當前的設置是這樣的:

╔═════╦═════════════╦══════╦═══════════╦═══════════╗ 
║ id ║ date  ║ uid ║ source ║ pageviews ║ 
╠═════╬═════════════╬══════╬═══════════╬═══════════╣ 
║ 1 ║ 2013-12-11 ║ 111 ║ source1 ║ 14  ║ 
║ 3 ║ 2013-12-11 ║ 111 ║ source1a ║ 1  ║ 
║ 11 ║ 2013-12-11 ║ 222 ║ source1 ║ 3  ║ 
║ 19 ║ 2013-12-11 ║ 222 ║ source1a ║ 11  ║ 
╚═════╩═════════════╩══════╩═══════════╩═══════════╝ 

我想考慮源1和source1a等於和合並兩個,要得到這樣的:

╔═════╦═════════════╦══════╦══════════╦═══════════╗ 
║ id ║ date  ║ uid ║ source ║ pageviews ║ 
╠═════╬═════════════╬══════╬══════════╬═══════════╣ 
║ 1 ║ 2013-12-11 ║ 111 ║ source1 ║ 15  ║ 
║ 2 ║ 2013-12-11 ║ 222 ║ source1 ║ 14  ║ 
╚═════╩═════════════╩══════╩══════════╩═══════════╝ 

id並不重要,我曾計劃重新增加新表中的id,結果爲

這是我試過的,但它沒有合併兩個記錄 - 我得到了匹配值,但s直到分開行:

SELECT date, uid, (SELECT CASE 
WHEN source = 'source1a' THEN 'source1' 
ELSE source 
END) AS 'source', pageviews 
FROM trafficSourceMedium 
GROUP BY date, source, userid 
+0

你需要case語句在GROUP BY太 – exussum

+0

在哪裏「1」和「2」從何而來? – Strawberry

回答

2

聚集查詢應該做你想要什麼:

select `date`, uid, 
     (case when source = 'source1a' then 'source1' else source end) as source, 
     sum(pageviews) as pageviews 
from trafficSourceMedium 
group by `date`, uid, 
      (case when source = 'source1a' then 'source1' else source end); 
相關問題