[英]SQL query calculating 2 separate columns of data based on date range group by size and type
I have 2 separate sql queries (shown below) that work well but I need to show the data in one table as begInv, acqQty, isize, type. 我有2个单独的sql查询(如下所示),效果很好,但我需要将数据作为begInv,acqQty,isize,type显示在一个表中。 How do I show the 2 columns together with separate date ranges in the same table for the given size and type? 对于给定的大小和类型,如何在同一表格中显示2列以及单独的日期范围?
SELECT
Sum(i.Qty) as begInv
,i.Size
,i.Type
FROM InvDetails i
join Acquisition a
on i.SerialNo = a.SerialNo
where a.DtAcquired < '1/25/2014'
group by i.Size, i.Type
SELECT
Sum(i.Qty) as acqqty
,i.Size
,i.Type
FROM InvDetails i
join Acquisition a
on i.SerialNo = a.SerialNo
where a.DtAcquired between '1/25/2014' and '3/15/2014'
group by i.Size, i.Type
The data would look like that when combined: begInv acqqty Size Type 0 5 Pint ice cream 0 6 16 oz soda 1 8 gallon soda 3 46 5 oz. 合并后的数据看起来像是:begInv acqqty大小类型0 5品脱冰淇淋0 6 16盎司汽水1 8加仑苏打3 46 5盎司。 soda 0 15 50 ML soda 0 11 5 ML soda 0 9 7 Ounce cream 1 12 Pint cream 1 4 75 ML milk 1 6 Pint milk 苏打0 15 50 ML苏打0 11 5 ML苏打0 9 7盎司奶油1 12品脱奶油1 4 75 ML牛奶1 6品脱牛奶
Thanks! 谢谢!
You want to use conditional aggregation: 您要使用条件聚合:
SELECT Sum(case when a.DtAcquired < '2014-01-25'
then i.Qty
else 0
end) as begqty,
Sum(case when a.DtAcquired between '2014-01-25' and '2014-03-15'
then i.Qty
else 0
end) as acqqty,
i.Size, i.Type
FROM InvDetails i join
Acquisition a
on i.SerialNo = a.SerialNo
group by i.Size, i.Type;
Note that I changed the date formats to use ANSI standard format; 请注意,我将日期格式更改为使用ANSI标准格式。 this is a bit safer than the form you used (which can be ambiguous as to whether it is mmddyyyy or ddmmyyyy). 这比您使用的表单安全一些(它是mmddyyyyy还是ddmmyyyy可能会模棱两可)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.