我有两张表,如下面
书
id TID reserveddate fee1 fee2 fee3 Noofplayers total
-------------------------------------
1 11 2012-11-25 100 200 300 3 800
2 12 2012-11-25 100 200 300 3 800
3 13 2012-11-28 200 100 200 1 500
球员
TID fee1 fee2
-------------------------------------
11 100 200
11 100 200
11 100 200
12 100 200
12 100 200
12 100 200
13 200 100
现在我想通过Reserveddate从两个表中检索数据。
我有一个查询,
select sum(b.fee1)+sum(b.fee2)+sum(a.fee3) as total
from Players b,book a where a.TID = b.TID and a.ReservedDate ='25-nov-2012'
group by a.ReservedDate
以上查询总和(fee3)添加3(noofplayers)次我想添加一本时间表表。
请按照客户要求更新查询...
答案 0 :(得分:1)
我相信这会奏效,总共会给出2400:
select sum(b.fee1_fee2_totalPerPlayer) + sum(a.fee3) as total
from book a
join (
select TID,
sum(fee1) + sum(fee2)
as fee1_fee2_totalPerPlayer
from Players
group by TID
) b on
a.TID = b.TID
where a.ReservedDate ='2012-11-25'
group by a.ReservedDate
以下是计算总数的方法:
对于TID = 11:300(Players.fee1的总和)+ 600(Players.fee2的总和)= 900
对于TID = 12:300(Players.fee1之和)+ 600(Players.fee2之和)= 900
900 + 900 = 1800
1800 + 600(日期'2012-11-25'的Book.fee3总和)= 2400
以下是一个示例: SQL Fiddle
答案 1 :(得分:0)
所以你想每天SUM
?您可以使用带SUM(...)OVER
的CTE:
WITH CTE AS
(
SELECT b.id, b.TID AS bTID, b.reserveddate, b.fee1, b.fee2, b.fee3, b.Noofplayers
, p.TID AS pTID, p.fee1 AS pFee1, p.fee2 AS pFee2
, SUM(b.fee1 + b.fee2 + a.fee3) OVER (PARTITION BY DATEADD(day, DATEDIFF(dd, 0, ReservedDate), 0)) As total
, DATEADD(day, DATEDIFF(dd, 0, ReservedDate), 0) AS ReservedDateDay
FROM Book b INNER JOIN Players p ON b.TID=p.TID
)
SELECT total FROM CTE WHERE ReservedDateDay='20121125';
答案 2 :(得分:0)
如果您确定 noofplayers 是播放器表中的条目数,您可以简单地将 fee3 的总和除以 noofplayer
select sum(b.fee1)+sum(b.fee2)+(sum(a.fee3)/noofplayer) as total
from Players b,book a where a.TID = b.TID and a.ReservedDate ='25-nov-2012'
group by a.ReservedDate
如果你不确定 noofplayer 是否正确,你可以在同一条记录上过滤玩家表,如
select sum(b.fee1)+sum(b.fee2)+sum(a.fee3) as total
from book a
join (select distinct TID, fee1, fee3 from players) as b
on a.TID = b.TID
where a.ReservedDate ='25-nov-2012'
group by a.ReservedDate