我有我认为是常见的问题,但我已经搜索过,找不到答案。
我有一个包含(简化)月,项目,类型,值
的大表Jan ProjectA X 15000,
Jan ProjectB X 2000,
Jan ProjectB Y 2000,
Jan ProjectC X 3000,
.....
Feb ProjectA X 15000,
Feb ProjectB Y 4000,
Feb ProjectC X 3000,
Feb ProjectD X 8989,
.....
Mar ProjectA X 15000,
Mar ProjectB Y 4000,
Mar ProjectC X 3000,
Mar ProjectD X 8989,
.....
我需要一个查询显示:
所有项目+在1月份输入,但不是2月份和 所有项目+在2月份输入,但不是1月份 所有项目+同时输入但具有不同的值
我需要在任何两个月之间抱歉不清楚
任何帮助都会非常感激(我已经尝试了使用NOT IN和连接的子查询,但我觉得我错过了一些简单的东西,因为我的查询变得非常大而且仍然没有用)
答案 0 :(得分:2)
您应该可以通过聚合执行此操作:
select project, type,
(case when sum(case when month = 'jan' then 1 else 0 end) > 0 and
sum(case when month = 'feb' then 1 else 0 end) = 0
then 'Jan-Only'
when sum(case when month = 'jan' then 1 else 0 end) = 0 and
sum(case when month = 'feb' then 1 else 0 end) > 0
then 'Feb-Only'
when max(case when month = 'jan' then value else 0 end) <>
max(case when month = 'feb' then value else 0 end)
then 'Different'
end) as Which
from largetable lt
group by project, type;
过滤掉jan和feb中值相等的最简单方法可能是使用子查询:
select t.*
from (select project, type,
(case when sum(case when month = 'jan' then 1 else 0 end) > 0 and
sum(case when month = 'feb' then 1 else 0 end) = 0
then 'Jan-Only'
when sum(case when month = 'jan' then 1 else 0 end) = 0 and
sum(case when month = 'feb' then 1 else 0 end) > 0
then 'Feb-Only'
when max(case when month = 'jan' then value else 0 end) <>
max(case when month = 'feb' then value else 0 end)
then 'Different'
end) as Which
from largetable lt
where month in ('jan', 'feb')
group by project, type
) t
where Which is not null;