我已经完成了这个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
所以基本上我想总结每个id的col1,并总结col1为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 :(得分: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'
这样的日期格式,也可以用于排序?
答案 1 :(得分:0)
CASE是你的朋友。一直使用它来报告,但速度很慢。
Select sum(col1) as Total,
sum(Case When id=7 Then col1 Else 0 End) as TotalId7,
...
From t1