SQL比较查询错误

时间:2014-11-07 19:39:01

标签: sql sql-server

我有一个有3年交易历史的表,我需要比较12个月的总和(交易)和总和(交易)4周,并显示带有结果集的客户清单。

Table Transaction_History

Customer_List  Transaction   Date
1                  200     01/01/2014
2                  200     01/01/2014
1                  100     10/24/2014
1                  100     11/01/2014
2                  200     11/01/2014

输出应该只有Customer_List为1,因为12个月的交易总和等于1个月交易的总和。

我很困惑如何找到12个月的总和,然后与相同的表总和比较4周。

4 个答案:

答案 0 :(得分:2)

下面的查询将起作用,但样本数据没有意义

数据集中过去12个月的客户1总计= 400 数据集中过去4周内客户1的总数= 200

除非您想排除过去4周,而不是过去12个月的一部分?

然后你会将“having子句”改为:

having
sum(case when Dt >= '01/01/2014' and dt <='12/31/2014' then (trans) end) - sum(case when Dt >= '10/01/2014' and dt <= '11/02/2014' then (trans) end) = 
    sum(case when Dt >= '10/01/2014' and dt <= '11/02/2014' then (trans) end)

当然这样做意味着您的结果将是客户1和2

 create table #trans_hist
(Customer_List int, Trans int, Dt Date)

insert into #trans_hist (Customer_List, Trans , Dt ) values 
(1,                  200,     '01/01/2014'),
(2,                  200,     '01/01/2014'),
(1,                  100,     '10/24/2014'),
(1,                  100,     '11/01/2014'),
(2,                  200,     '11/01/2014')

select 

Customer_List




from #trans_hist

group by 
Customer_List


having
sum(case when Dt >= '01/01/2014' and dt <='12/31/2014' then (trans) end) = 
    sum(case when Dt >= '10/01/2014' and dt <= '11/02/2014' then (trans) end)





drop table #trans_hist

答案 1 :(得分:1)

我建议自我加入。

select yourfields
from yourtable twelvemonths join yourtable fourweeks on something
where fourweek.something is within a four week period
and twelvemonths.something is within a 12 month period

你应该能够弄清楚细节。

答案 2 :(得分:1)

如果您的交易总是积极的,并且您希望12个月总计等于4周总额的客户,那么您希望客户在过去四周内进行交易,而不是在过去12个月内进行交易 - 4周。

您可以使用聚合和having子句更直接地获取此内容。逻辑是检查过去4年之前发生的任何交易:

select Customer_List
from Transaction_History
where date >= dateadd(month, -12, getdate())
group by CustomerList
having min(date) >= dateadd(day, -4 * 7, getdate());

答案 3 :(得分:0)