0

我有一个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 作为查询参数并希望查看:

  1. 所选时间段内每个月的用户总数(!不是每月的计数,而是截至(包括)当月的用户总数。)。
  2. 在本月创建至少一张发票的用户计数,每个月再次创建。
  3. 每个月的发票计数(此处为每月计数)。

示例:期间: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 日,我得到了 2 月。- 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

我想在一个查询中完成这项工作,正如我所说,希望每个月都有信息,即使信息与上个月相同。我怎样才能达到我想要的结果,有什么想法吗?

4

1 回答 1

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
于 2013-05-29T14:43:46.500 回答