我已经看过这个问题(Please help merging 4 MySQL queries to One)希望它会有所帮助,但事实并非如此。我无法理解它,因为我的大脑已经油炸了。
我试图将四个SELECT语句合并为一个单独的单个SELECT语句。
字段是;
QUANTITY:INT;
ORDERDATE:DATE; //不是日期时间 - 我不需要时间。
MySQL版本5.6.17
我检索的数据是;
1)本财政年度订购的产品数量;
SELECT SUM(QUANTITY) AS YTD
FROM ORDERDETAILS
WHERE ORDERDATE BETWEEN "2016-07-01" AND "2017-02-16"
请注意,在澳大利亚,财政年度是7月1日至6月30日。
2)本月订购的产品数量;
SELECT SUM(QUANTITY) AS MONTHY
FROM ORDERDETAILS
WHERE ORDERDATE BETWEEN "2017-02-01" AND "2017-02-16"
3)今天订购的产品数量;
SELECT SUM(QUANTITY) AS TODAYS
FROM ORDERDETAILS
WHERE ORDERDATE = "2017-02-16"
4)每个订单的平均订购产品数量
SELECT AVG(QUANTITY) AS BOOGER
FROM ORDERDETAILS
WHERE ORDERDATE BETWEEN "2016-07-01" AND "2017-02-16"
我想避免向服务器发送四个单独的语句。也许它无法完成,但如果我能在单一陈述中取得同样的结果,我会感到高兴。
我看过联接,在选择中嵌入选择,但无法理解它。
一旦我获得数据,我所做的就是更新表格上的几个标签(Delphi)。
近55岁的大脑可以处理的任何提示都将受到赞赏。
答案 0 :(得分:2)
您可以使用条件时执行此操作:
select
sum(case when ORDERDATE BETWEEN '2016-07-01' AND '2017-02-16' then QUANTITY end ) as YTD,
sum(case when ORDERDATE BETWEEN '2017-02-01' AND '2017-02-16' then QUANTITY end ) as MONTHY,
sum(case when ORDERDATE = '2017-02-16' then QUANTITY end ) as TODAYS,
AVG(case when ORDERDATE BETWEEN '2016-07-01' AND '2017-02-16' then QUANTITY end ) as BOOGER
FROM ORDERDETAILS
答案 1 :(得分:1)
您只需对表的不同调用使用不同的别名,并将其全部放在一个SELECT语句中,如下所示:
SELECT SUM(od1.QUANTITY) AS YTD,
SUM(od2.QUANTITY) AS MONTHLY,
SUM(od3.QUANTITY) AS TODAYS,
AVG(od4.QUANTITY) AS BOOGER
FROM ORDERDETAILS od1,
ORDERDETAILS od2,
ORDERDETAILS od3,
ORDERDETAILS od4
WHERE od1.ORDERDATE BETWEEN CAST('2016-07-01' AS DATE) AND CAST('2017-02-16' AS DATE)
AND od2.ORDERDATE BETWEEN CAST('2017-02-01' AS DATE) AND CAST('2017-02-16' AS DATE)
AND od3.ORDERDATE = CAST('2017-02-16' AS DATE)
AND od4.ORDERDATE BETWEEN CAST('2016-07-01' AS DATE) AND CAST('2017-02-16' AS DATE)
答案 2 :(得分:0)
使用SUM(IF())
模式并在IF
内移动条件。
SELECT
SUM(IF(ORDERDATE BETWEEN "2016-07-01" AND "2017-02-16", QUANTITY, 0)) AS YTD,
SUM(IF(ORDERDATE BETWEEN "2017-02-01" AND "2017-02-16", QUANTITY, 0)) AS MONTHY,
SUM(IF(ORDERDATE = "2017-02-16", QUANTITY, 0)) AS TODAYS,
SUM(IF(ORDERDATE BETWEEN "2016-07-01" AND "2017-02-16", QUANTITY, 0)) / COUNT(IF(ORDERDATE BETWEEN "2016-07-01" AND "2017-02-16", 1, NULL)) AS BOOGER
FROM ORDERDETAILS
WHERE ORDERDATE BETWEEN "2016-07-01" AND "2017-02-16";
考虑使用CURDATE()
作为今天的日期。
还可以添加WHERE
子句,以便不扫描表的所有行,例如WHERE ORDERDATE BETWEEN "2016-07-01" AND "2017-02-16"
之后FROM ORDERDETAILS