我将演示一个简单的问题示例,而不是从我的项目中查看长sql查询。
我的例子是:
Select DeliveryAddressID, PickupDate, TotalWeight, count(DeliveryAddressID) AS Packages
From DeliveryDB
Where Date1 >= '10-12-2013' AND Date2 <= '15-12-2013'
Group By PickupDate, DeliveryAddressID
我的结果将是:
我想要实现的是为所有4个包获取此DeliveryAddressID,但仍保留总数。这就是这样的。
我想要的是预期结果:
我想这样做的原因是因为通过这种方式,我将能够跟踪每个包裹的条形码,并且还能够跟踪更多细节。
干杯: - )
答案 0 :(得分:2)
在大多数数据库中,您可以使用窗口函数执行此操作:
Select DeliveryAddressID, PickupDate, TotalWeight,
count(DeliveryAddressID) over (partition by PickupDate, DeliveryAddressID) AS Packages
From DeliveryDB
Where Date1 >= '10-12-2013' AND Date2 <= '15-12-2013';
这将返回所有四行的总数。
编辑:
你可以用同样的方式处理TotalWeight
(这不是原始问题的一部分):
Select DeliveryAddressID, PickupDate,
count(DeliveryAddressID) over (partition by PickupDate, DeliveryAddressID) AS Packages,
CEILING(SUM(CASE When (Weight <> 0 AND Volumen <> 0) AND Weight >= (Volumen * @zeroVoluFac)
Then Weight
end) over (partition by PickupDate, DeliveryAddressID)
) as TotalWeight
From DeliveryDB
Where Date1 >= '10-12-2013' AND Date2 <= '15-12-2013';
答案 1 :(得分:1)
我无法做到这一点,但你会接受细节后的总行数而不是第一行N
行的总数和最后一行的总数,如下所示:
IdCode Weight PickupDate
----------- ----------- -------------------------
12345 5 2013-01-07 00:00:00.0
12345 10 2013-01-07 00:00:00.0
12345 15 2013-01-07 00:00:00.0
12345 20 2013-01-07 00:00:00.0
(4 rows)
Sum(Weight) Count(IdCode)
----------- -------------
50 4
如果您对我有任何用处,我使用的SQL是(抱歉不匹配的列名)
Select IdCode, Weight, PickupDate
From DeliveryDB
Group By PickupDate, IdCode
ORDER BY PickupDate, IdCode
COMPUTE sum(Weight), count(IdCode) by PickupDate, IdCode
COMPUTE
在Group By
的休息时间提供总计或其他汇总。