1

我有两个如下表

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

以上查询在 sum(fee3) 添加 3(noofplayers) 次我想添加一个时间表。

您能否根据客户要求更新查询...

4

3 回答 3

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

于 2012-11-28T12:39:03.593 回答
0

所以你想SUM每天?您可以将 CTE 与SUM(...)OVER

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';
于 2012-11-28T12:10:04.273 回答
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
于 2012-11-28T12:12:31.360 回答