我有一张包含各种订单的表格:
ID | Date | etc...
1 | 2013-01-01 | etc
2 | 2013-02-01 | etc
3 | 2013-03-01 | etc
4 | 2013-04-01 | etc
5 | 2013-05-01 | etc
6 | 2013-06-01 | etc
7 | 2013-06-01 | etc
8 | 2013-03-01 | etc
9 | 2013-04-01 | etc
10 | 2013-05-01 | etc
我想要一个以结果结束的查询:
overallTotal | totalThisMonth | totalLastMonth
10 | 2 | 1
但我想在一个查询中执行此操作!我试图找到一种方法来使用子查询来执行此操作。我到目前为止:
SELECT * from (
SELECT count(*) as overallTotal from ORDERS
)
如何将其与其他子查询结合使用,以便我可以在一个查询中获得总数?
更新
最初的问题是针对MySQL,但我现在需要Firebird。
答案 0 :(得分:2)
使用条件求和,你可以做到(MySQL语法):
select
count(*) as overallTotal,
sum(if(Month(Date)+12*Year(Date)=Month(GetDate())+12*Year(GetDate()), 1, 0))
as totalThisMonth
sum(if(Month(Date)+12*Year(Date)=Month(GetDate())+12*Year(GetDate())-1, 1, 0))
as totalThisMonth;
from mytable
使用month+12*year
公式来避免年度变化问题。
<强>更新强>
使用 Firebird 同样适用,您只需将Month(x)
替换为EXTRACT (MONTH FROM x)
,将Year(x)
替换为EXTRACT (YEAR FROM x)
和Getdate()
与CURRENT_TIME
。这看起来很难看,所以我不会把它放在这里,但你可以自己轻松做到。
答案 1 :(得分:0)
Posubly使用IF语句结果的SUM,IF检查它是否是相关日期。
SELECT COUNT(*),
SUM(IF(YEAR(Date) = YEAR(CURDATE()) AND MONTH(Date) = MONTH(CURDATE()), 1, 0))
SUM(IF((YEAR(Date) = YEAR(CURDATE()) AND MONTH(Date) = MONTH(CURDATE()) - 1) OR (YEAR(Date) = YEAR(CURDATE()) - 1 AND MONTH(Date) = 12 AND MONTH(CURDATE()) = 1), 1, 0))
from ORDERS
复杂性是由于在寻找上个月时应对年度变化而引起的
答案 2 :(得分:0)
SELECT
(SELECT COUNT(*) FROM C AS total) AS T,
(SELECT COUNT(*) AS thisMonth FROM C WHERE MONTH(d) = 6) AS A,
(SELECT COUNT(*) AS lastMonth FROM C WHERE MONTH(d) = 5) AS B;
请注意“月份”是“硬编码” - 但在应用程序级别提取“当前月份”应该不会太困难。如果你真的需要,你可以在SQL级别上使用之类的:
SELECT
(SELECT COUNT(*) FROM C AS total) AS T,
(SELECT COUNT(*) AS thisMonth FROM C WHERE MONTH(d) = MONTH(NOW()) ) AS A,
(SELECT COUNT(*) AS lastMonth FROM C WHERE MONTH(d) = (MONTH(NOW())+11)%12) ) AS B;
答案 3 :(得分:0)
我发现你已经在使用子查询,所以为什么不做类似下面的事情,
SELECT
(SELECT count(*) from ORDERS) as overallTotal,
(SELECT count(*) from ORDERS where Date between ... and ...) as totalThisMonth,
(SELECT count(*) from ORDERS where Date between ... and ...) as overallTotal