2014-01-25 26 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'? –

相关问题