2014-01-25 29 views
0

香港專業教育學院這樣做的SQL,但我需要一些幫助改變它按月總結同一列兩次在同一個表月份不同的標準

select id, (select sum(col1) from t1) as totalcol1, 
(select sum(col1) from t1 where id = 7) as total_for_id from t1 
group by id 

所以基本上我想總結一下COL1每一個ID,也總結up col1 for where id = 7,全部來自同一張表t1。我希望能夠通過創建日期和月份來擴展此查詢,並且每種方法我都會嘗試保持獲取太多值錯誤或者子查詢檢索多行值。所以像

select (select to_char(view_date,'Mon-YY') from t1 group by to_char(view_date,'Mon-YY')) 
as month, id, (select sum(col1) from t1 where view_date between '30-nov-2013' and '01-dec- 
2013') as totalcol1, (select sum(col1) from t1 where id = 7 and view_date between '30-nov-2013' and '01-dec-2013') 
as total_for_id from t1 
group by id 

我意識到這是可憐的,任何解決方案,將不勝感激

好吧,我可能也顯示出它的一個輸出我想

month --|- id --|--- sum(col1 where id = 7) --|---sum(col1) 

nov-13 --- 7 --------------100--------------- 1000 

dec-13 --- 7 -------------- 200 -------------- 1500 
+0

您的問題標籤爲[tag:mysql](一種跨平臺的開源RDBMS,現在由Oracle擁有)和[tag:sql-server](來自Microsoft的專有的閉源RDBMS)。你在用哪個? – eggyal

+0

RDBMS的用途是什麼?它支持分析功能嗎? –

+0

請發佈所需格式的結果,因爲它是如何設想它是絕對不清楚的。您'GROUP BY id'將在其行中顯示'id = 7'的結果。 –

回答

0

的情況是你的朋友。一直使用這個報告,但它很慢。

Select sum(col1) as Total, 
    sum(Case When id=7 Then col1 Else 0 End) as TotalId7, 
    ... 
From t1 
+0

我理想的是希望id在行上顯示,儘管如此,這意味着添加一個where id = 7,這會搞砸和(col1) – bram91

2

這是你想要的嗎?

select to_char(view_date, 'Mon-YY'), 7 as id, 
     sum(col1) as totalcol1, 
     sum(case when id = 7 then col1 else 0 end) as total_for_id7 
from t1 
group by to_char(view_date, 'Mon-YY') 
order by min(view_date); 

我加了order by,所以結果會按日期順序。您是否考慮過使用'YYYY-MM'這樣的日期格式,它也可以用於排序?

+0

那麼......如果這確實是OP想要(也可能是這種情況),你是一個心靈讀者。 –

+0

不會包含一個id列雖然,想要一個說id = 7 – bram91

+0

@ bram91。 。 。如果按月份總結,你想要哪個'id'? –

相關問題