每天都有船只抵达一个有“P”级乘客的港口。每艘船的名称为“N”,每天最多到达一次。 我有一张这样的数据表:
Date N P
2013-11-27 A 12
2013-11-27 G 16
2013-11-27 B 56
2013-11-28 A 10
2013-11-29 B 19
2013-11-29 A 19
2013-11-30 G 18
2013-11-30 B 13
2013-11-30 A 11
我希望在给定的时间跨度内将一艘船的'A'乘客数量与另一艘'A'乘客数量进行比较,但仅限于他们在同一天到达时。结果是
Date PA PB
2013-11-27 12 56
2013-11-29 19 19
2013-11-30 11 13
注意28日没有'B',所以既没有报告(反之亦然)。
同桌上的某种外连接?
SELECT A.Date, A.P as PA, B.P AS PB
FROM Arrivals A OUTER JOIN Arrivals B ON A.Date = B.Date
WHERE ... ???
Date >= @start AND Date <= @end AND
A.N = 'A' AND B.N = 'B'
以上查询是我想到的开始,但我不知道如何完成它。有谁知道查询? SQL Server 2008 谢谢你的帮助。
答案 0 :(得分:1)
这有用吗?
SELECT A.Date, A.P as PA, B.P AS PB
FROM (Select * FROM Arrivals WHERE N = 'A') A
INNER JOIN (Select * FROM Arrivals WHERE N = 'B') B
ON A.Date = B.Date
答案 1 :(得分:0)
试试这个:
create table #tmp
(
dt date,
n varchar (1) ,
p int
)
GO
insert into #tmp
values
('2013-11-27' , 'A' , 12),
('2013-11-27' , 'G' , 16),
('2013-11-27' , 'B' , 56),
('2013-11-28' , 'A' , 10),
('2013-11-29' , 'B' , 19),
('2013-11-29' , 'A' , 19),
('2013-11-30' , 'G' , 18),
('2013-11-30' , 'B' , 13),
('2013-11-30' , 'A' , 11)
GO
select distinct
a.dt,
(select SUM(p) from #tmp y where y.dt = a.dt and y.n = 'A') pa,
(select SUM(p) from #tmp y where y.dt = a.dt and y.n = 'B') pb,
(select SUM(p) from #tmp y where y.dt = a.dt and y.n = 'G') pG
from #tmp a
group by a.dt, a.n
Go
drop table #tmp
答案 2 :(得分:0)
;WITH ARRIVAL_A AS
(SELECT DATE, P FROM ARRIVALS WHERE N = 'A'),
ARRIVAL_B AS
(SELECT DATE, P FROM ARRIVALS WHERE N = 'B')
SELECT ARRIVAL_A.DATE, ARRIVAL_A.P [PA], ARRIVAL_B.P [PB]
FROM ARRIVAL_A INNER JOIN ARRIVAL_B
ON ARRIVAL_A.DATE = ARRIVAL_B.DATE