单个查询以从多个表中检索多个值

时间:2016-04-21 14:19:40

标签: mysql database

费用表

1/1/2016  exp1  2000
13/1/2016 exp11 2500
1/2/2016  exp2  1500
1/3/2016  exp3  1000
10/3/2016 exp1  2000

收入表

1/1/2016  income1 2500
1/2/2016  income2 3500
1/3/2016  income3 1500
10/3/2016 income3 1000
1/4/2016  income4 5000

从单一查询我需要的是按月分组,这是我需要的

Expenses Incomes Month
4500     2500    Jan
1500     3500    Feb
3000     2500    Mar
0        5000    April

我需要上述查询才能在Google图表中显示数据

2 个答案:

答案 0 :(得分:0)

糟糕的数据结构和格式,但并非不可能:

SELECT 
    IFNULL(exp.Expenses,0) Expenses, 
    IFNULL(inc.Incomes,0) Incomes, 
    inc.`monthname` `Month`
FROM
    (
        SELECT
            SUM(i.amount) Incomes,
            MONTHNAME(STR_TO_DATE(i.`date`, '%d/%m/%Y')) `monthname`,
            MONTH(STR_TO_DATE(i.`date`, '%d/%m/%Y')) `month`
        FROM
            incomes i
        GROUP BY
            MONTHNAME(STR_TO_DATE(i.`date`, '%d/%m/%Y')),
            MONTH(STR_TO_DATE(i.`date`, '%d/%m/%Y'))
    ) inc

LEFT JOIN

    (
    SELECT
        SUM(e.amount) Expenses,
        MONTHNAME(STR_TO_DATE(e.`date`, '%d/%m/%Y')) `monthname`,
        MONTH(STR_TO_DATE(e.`date`, '%d/%m/%Y')) `month`
    FROM
        expenses e
    GROUP BY
        MONTHNAME(STR_TO_DATE(e.`date`, '%d/%m/%Y')),
        MONTH(STR_TO_DATE(e.`date`, '%d/%m/%Y'))
    ) exp
ON exp.`month` = inc.`month`

ORDER BY
    inc.`month`

这种简单的输出:

+----------+---------+----------+
| Expenses | Incomes | Month    |
+----------+---------+----------+
| 4500     | 2500    | January  |
| 1500     | 3500    | February |
| 3000     | 2500    | March    |
| 0        | 5000    | April    |
+----------+---------+----------+
4 rows in set

无论如何,最重要的是如何改进和规范化数据。

答案 1 :(得分:0)

在我的解决方案中,我给出的是月份而不是文本。如果您愿意,我会留给您将其转换为文本(例如,使用CASE表达式):

SELECT
    sum(expense) AS total_expense, sum(income) AS total_income, trans_month
FROM (
    SELECT
        month(trans_date) AS trans_month,
        0 AS income,
        sum(amount) AS expense
    FROM expense
    GROUP BY month(trans_date)
    UNION ALL
    SELECT
        month(trans_date) AS trans_month,
        sum(amount) AS income,
        0 AS expense
    FROM income
    GROUP BY month(trans_date)
) AS a
GROUP BY trans_month;