T-SQL Group By和Sub Query

时间:2014-06-03 13:49:13

标签: sql sql-server tsql group-by

我知道我的查询有什么问题,但我真的很难找到解决方案。

SQL Fiddle

我想我甚至不确定如何问这个问题。我想要实现的是对按分支分组的日期范围的所有跟踪号进行求和,但(并且这是踢球者)包括具有相同跟踪号的总和中的任何其他记录。我想过做这样的事情,但当然SQL Server不喜欢这个,因为我在聚合函数中不能有子查询。

MAX((select SUM(demo.NegotiatedRate) where #demo.Tracking = demo2.Tracking)) as NegotiatedRate

如果有人不想点击SQL Fiddle链接

,这是我到目前为止的查询
select     demo.Branch, 
           SUM(demo.NegotiatedRate) as NegotiatedRate,
           SUM(demo2.BillRate) as BillRate
from       demo
join       demo2 on demo2.Tracking = demo.Tracking
where      demo.ShipDate = '2014-05-01'
group by   demo.Branch

预期输出

我想要实现的输出看起来像这样。 GH6协商的费率和帐单费率应该匹配,即使其中一个GH6条目超出了所需的日期范围。

Branch    NegotiatedRate    BillRate
GH4       50                50
GH6       25                25

3 个答案:

答案 0 :(得分:4)

您可以在单独的派生表或cte中预先计划整体(非日期范围绑定,未过滤)总计,然后再加入其中:

WITH totals AS
(
  SELECT demo.Tracking,
     SUM(demo.NegotiatedRate) as NegotiatedRate
  from       demo
  group by   demo.Tracking
)
select     demo.Branch, 
           MIN(totals.NegotiatedRate) as NegotiatedRate,
           SUM(demo2.BillRate) as BillRate
from       demo
join       demo2 on demo2.Tracking = demo.Tracking
join       totals on totals.Tracking = demo.Tracking
where      demo.ShipDate = '2014-05-01'
group by   demo.Branch;

SqlFiddle here

鉴于每次跟踪应该只有一个NegotiatedRate,您可以避免通过应用聚合(我使用{{1}来将总和totals.NegotiatedRate添加到外部查询中虽然这只是为了安抚Sql。

答案 1 :(得分:1)

作为一个更简单的答案,你可以做类似的事情:

SELECT     demo.Branch, 
           SUM(demo.NegotiatedRate) AS NegotiatedRate,
           demo2.BillRate
FROM       demo
JOIN       demo2 on demo2.Tracking = demo.Tracking
WHERE      demo.Tracking IN
           (
               SELECT Tracking
               FROM demo
               WHERE ShipDate = '2014-05-01'
           )
GROUP BY   demo.Branch, demo2.BillRate

据我所知,您可以在特定日期范围内获得所需的所有跟踪号码,然后从这些跟踪号码中获取所有信息,无论日期范围如何。然后按Branch和BillRate对它们进行分组,每个跟踪号都应该是一个值。

答案 2 :(得分:0)

如果我理解正确,您希望在其中一个日期是所选日期时包括所有行。如果这是正确的,那么您需要having子句中的逻辑,而不是where子句中的逻辑:

select     demo.Branch, 
           SUM(demo.NegotiatedRate) as NegotiatedRate,
           SUM(demo2.BillRate) as BillRate
from       demo
join       demo2 on demo2.Tracking = demo.Tracking
group by   demo.Branch
having sum(case when demo.ShipDate = '2014-05-01' then 1 else 0 end) > 0