我遇到mysql查询问题,希望有人帮助我。
我有以下表格:
CREATE TABLE USER
(
ID VARCHAR(80) NOT NULL,
REGISTRATION_DATE DATE NOT NULL,
.....
PRIMARY KEY(ID)
);
CREATE TABLE INVOICES
(
USER_ID VARCHAR(80) NOT NULL,
INVOICE_NUMBER VARCHAR(50) NOT NULL,
CREATION_DATE DATE NOT NULL,
........
PRIMARY KEY(USER_ID, INVOICE_NUMBER),
FOREIGN KEY(USER_ID) REFERENCES USER(ID)
);
我需要以下功能:我选择开始和结束日期(时间段),例如01.02.2013-31.05.2013作为查询的参数,并希望看到:
示例:期间:01.02.2013-31.05.2013 结果集:
Month | Year | Total count of users | Count of users who created at least one invoice in this month | Count of invoices in this month
Febr | 2013 | 20 | 12 | 45
March | 2013 | 20 | 4 | 22
April | 2013 | 23 | 20 | 30
May | 2013 | 28 | 27 | 69
是否可以编写此类查询? 我试过这个:
SELECT YEAR, MONTH, @VAR := @VAR + TOTS.COUNT AS USERS_TOTAL
FROM (
SELECT
YEAR(REGISTRATION_DATE) AS YEAR,
MONTH(REGISTRATION_DATE) AS MONTH,
COUNT(ID) AS COUNT
FROM USER
WHERE REGISTRATION_DATE <= '2013-05-31'
GROUP BY YEAR, MONTH
) AS TOTS, (SELECT @VAR := 0) AS INC
我获得了用户总数,但仅限于有一些新的注册用户。我的意思是,如果Ferb的用户总数。而在3月是20,在4月21日,我得到了 Febr。 - 20,没有3月和4月21日的信息,我需要从选择期间开始每个月的信息。
通过此查询,我获得了至少创建了一张发票的用户数,但如果计数与前几个月的计数相同,则会再次获得 - 无信息:
SELECT YEAR(CREATION_DATE) as YEAR, MONTH(CREATION_DATE) as MONTH,
COUNT(DISTINCT CUSTOMER_ID)
FROM INVOICES
WHERE CREATION_DATE >= '2013-02-01' AND CREATION_DATE <='2013-05-31'
GROUP BY YEAR, MONTH
通过此查询,我可以获得选择期间每个月的发票数量:
SELECT YEAR(CREATION_DATE) as YEAR, MONTH(CREATION_DATE) as MONTH, COUNT(INVOICE_NUMBER)
FROM INVOICES
WHERE CREATION_DATE >= '2013-02-01' AND CREATION_DATE <='2013-05-31'
GROUP BY YEAR, MONTH
我希望在单个查询中完成这项工作,正如我所说,希望每个月都有信息,即使信息与上个月相同。 我怎么能达到我想要的结果,任何想法?
答案 0 :(得分:0)
分别生成它们非常简单。但是如果你想把它们放在一个查询中,这可能会很混乱。在不同的步骤中完成它们可能会更好。但这是我的尝试
SELECT
extract(MONTH FROM i.date) AS MONTH,
extract(YEAR FROM i.date) AS YEAR, count(i.*) AS Count_Invoices,
count(user.*) as count_users,
CASE (WHERE i.* IS NOT NULL COUNT u.id END) AS active_users_this_month
FROM
invoices I RIGHT JOIN users u
GROUP BY
Year, Month