我试图找到2013年和2014年T恤销售的差异。这2个查询本身确实给了我正确的销售数量。但是,我不知道如何比较这两个数字并返回它们的区别。有什么帮助吗?
select sum(qty)
from customers natural join orders
natural join itemsordered
natural join items
where orderdate >= '2014-01-01' and orderdate <= '2014-12-31' and description ='tshirt';
select sum(qty)
from customers natural join orders
natural join itemsordered
natural join items
where orderdate >= '2013-01-01' and orderdate <= '2013-12-31' and description ='tshirt';
使用的数据库如下:
客户(custID,name,firstOrderDate,city)
经理(mgrID,姓名,薪水)
商店(storeID,city,mgrID)
项目(itemID,描述,大小,颜色)
库存(storeID,itemID,数量)
订单(orderID,orderDate,custID)
ItemsOrdered(itemID,orderID,qty)
答案 0 :(得分:2)
您在SUM()函数中使用case表达式。在这里,您只过滤您感兴趣的2年的所有记录,然后使用案例,2013年总和记录,2014年记录总和,然后从另一个中减去其中一个。像这样:
select
sum(case when orderdate >= '2013-01-01' and orderdate < '2014-01-01' then qty end) yr2013
, sum(case when orderdate >= '2014-01-01' and orderdate < '2015-01-01' then qty end) yr2014
, sum(case when orderdate >= '2014-01-01' and orderdate < '2015-01-01' then qty end)
- sum(case when orderdate >= '2013-01-01' and orderdate < '2014-01-01' then qty end) diff
from customers
natural join orders
natural join itemsordered
natural join items
where orderdate >= '2013-01-01' and orderdate < '2015-01-01' and description ='tshirt';
请注意我在日期范围逻辑中引入的小改动。使用“大于等于”与“小于(第二天)”的组合比在下边界和上边界中涉及等于更可靠。 (&amp;它适用于任何日期/时间精度,不会造成任何间隙或重叠。)
注意:以上内容应该相当通用,但处理日期的方法会因数据库类型(编写时未知)而有所不同
答案 1 :(得分:0)
另一种方法是将两年行转移到一行并执行差异。
select diff = abs(y13_qty - y14_qty) from
(select yr = year(orderdate), qty
from customers natural join orders
natural join itemsordered
natural join items
where year(orderdate) in (2013,2014) and description ='tshirt')
pivot (sum(qty) as qty for yr in (2013 as 'y13', 2014 as 'y14'))
(不熟悉oracle所以可能会关闭pivot语法)