如何在SQL查询中分组后进行相互比较?

时间:2012-10-31 07:34:40

标签: sql sql-server

我有一张表Information,它是这样的:

ID    From     To        Product          Date  
1         A         B          ProdA         2012-10-01  
2         A         B          ProdA         2012-10-13  
3         A         B          ProdB         2012-10-17  
4         A         B          ProdC         2012-10-18  
5         A         C          ProdB         2012-10-02  
6         A         C          ProdC         2012-10-04  
7         A         C          ProdD         2012-10-12  
8         A         C          ProdE         2012-10-14  
9         A         D          ProdA         2012-10-11  
10       A         D          ProdA         2012-10-14  

让我们将From和To的组合称为关系。所以(A,B)和(A,C)是关系 我需要做的是找到在一周时间内发送/接收不同产品的关系。所以在上面的例子中,查询应该返回:

A    B
A    C

因为这些行匹配:

2         A         B          ProdA         2012-10-13  
3         A         B          ProdB         2012-10-17  
4         A         B          ProdC         2012-10-18  

5         A         C          ProdB         2012-10-02  
6         A         C          ProdC         2012-10-04  

7         A         C          ProdD         2012-10-12  
8         A         C          ProdE         2012-10-14  

我知道我应该从SELECT ID, From, To, Product, Date FROM Information GROUP BY From, To开始,但我不知道下一步是什么。有什么帮助吗?

2 个答案:

答案 0 :(得分:1)

select Distinct [From],[TO],year([Date]) as y ,datepart(wk,[Date]) as w
into #tmp
From Tablex

Select t1.*
from #tmp t1
Join #tmp t2 on t1.From=t2.From and t1.y=t2.y and t1.w=t2.y and t1.to<>t2.to
 Drop table #tmp

答案 1 :(得分:1)

或许这样的事情:

declare @t table(id int identity(1,1), [from] char default 'A', [to] char, product char(5), date date)
-- populating testdata works with sql server 2008+
insert @t ([to],product, date) values
('B','ProdA','2012-10-01'),('B','ProdA','2012-10-13'),
('B','ProdB','2012-10-17'),('B','ProdC','2012-10-18'),
('C','ProdB','2012-10-02'),('C','ProdC','2012-10-04'),
('C','ProdD','2012-10-12'),('C','ProdE','2012-10-14'),
('D','ProdA','2012-10-11'),('D','ProdA','2012-10-14')


select * from @t t where exists 
(select 1 from @t where t.[from] = [from] and t.[to] = [to] and 
t.product <> product and t.date between dateadd(day, -7, date) and 
dateadd(day, 7, date))