我正在尝试编写一个查询来比较两个日期范围的数据。
第一个日期范围:
select code,description, quantity*each as Total
from orderiteminfo oi, orderinfo o, invoiceinfo i
where oi.orderid = o.orderid
and o.invoiceid = i.invoiceid
and i.invdate between '2014-01-01' and '2014-02-01'
group by oi.code, description, quantity, each
第二个日期范围:
select code,description, quantity*each as Total
from orderiteminfo oi, orderinfo o, invoiceinfo i
where oi.orderid = o.orderid
and o.invoiceid = i.invoiceid
and i.invdate between '2015-01-01' and '2015-02-01'
group by oi.code, description, quantity, each
我希望结果如下:
代码|描述|第一个日期范围的总计|第二个日期范围的总计
答案 0 :(得分:1)
像这样的东西
all
作为旁注,总是使用all
语法来连接两个表而不是旧式逗号分隔连接,并将过滤器单独保留在SELECT code,
description,
SUM(CASE
WHEN i.invdate BETWEEN '2014-01-01' AND '2014-02-01' THEN quantity * each
END) AS [Total for First Date Range],
SUM(CASE
WHEN i.invdate BETWEEN '2015-01-01' AND '2015-02-01' THEN quantity * each
END) AS [Total for second Date Range]
FROM orderiteminfo oi
INNER JOIN orderinfo o
ON oi.orderid = o.orderid
INNER JOIN invoiceinfo i
ON o.invoiceid = i.invoiceid
WHERE ( i.invdate BETWEEN '2014-01-01' AND '2014-02-01'
OR i.invdate BETWEEN '2015-01-01' AND '2015-02-01' )
GROUP BY oi.code,
description
子句中,这更易于阅读
答案 1 :(得分:0)
如果我理解正确,我认为您宁愿使用case when
语句在单个查询中执行此操作:
select code,
description,
case
when i.invdate between '2014-01-01' and '2014-02-01'
then quantity*each
end Total_for_First_Date_Range,
case
when i.invdate between '2015-01-01' and '2015-02-01'
then quantity*each
end Total_for_Second_Date_Range
from orderiteminfo oi, orderinfo o, invoiceinfo i
where oi.orderid = o.orderid
and o.invoiceid = i.invoiceid
group by oi.code, description, quantity, each; --not sure if you need this