好的,这笔交易我得到了一张包含大量客户信息的表格。 每个客户每年最多进行一次购买,由一行代表。 这一年有一列,并且有一列包含每个客户的唯一标识符。我需要做的是构建一个去年和今年的查询,并告诉我去年哪些客户在这里购买但今年没有购买。
我还需要建立一个查询,告诉我去年和前年哪些客户没有购买,但今年确实购买了。
答案 0 :(得分:4)
鉴于此表:
Purchase
========
PurchaseID (autoincrement int PK)
ClientID (int FK)
Year (int)
Amount (float)
示例数据:
insert into Purchase (ClientID, Year, Amount) values (1, 2009, 123)
insert into Purchase (ClientID, Year, Amount) values (2, 2009, 123)
insert into Purchase (ClientID, Year, Amount) values (2, 2010, 123)
insert into Purchase (ClientID, Year, Amount) values (3, 2010, 123)
insert into Purchase (ClientID, Year, Amount) values (3, 2007, 123)
insert into Purchase (ClientID, Year, Amount) values (4, 2010, 123)
insert into Purchase (ClientID, Year, Amount) values (4, 2008, 123)
在2009年购买但未在次年(2010年)购买:
select p1.*
from Purchase p1
left outer join Purchase p2 on p1.ClientID = p2.ClientID and p1.Year = p2.Year - 1
where p2.ClientID is null
and p1.Year = 2009
结果:
PurchaseID Year ClientID Amount
----------- ----------- ----------- ---------------------
1 2009 1 123.00
2010年购买,但不是前两年(2008年或2009年):
select p3.*
from
Purchase p3
left outer join Purchase p2 on p3.ClientID = p2.ClientID and p3.Year = p2.Year + 1
left outer join Purchase p1 on p3.ClientID = p1.ClientID and p3.Year = p1.Year + 2
where p2.ClientID is null
and p1.ClientID is null
and p3.Year = 2010
结果:
PurchaseID Year ClientID Amount
----------- ----------- ----------- ---------------------
4 2010 3 123.00