年收入和支出表

时间:2017-12-16 12:01:52

标签: mysql database

我有两张桌子 的收入 (ID, 收入, 日期, 用户身份) 和桌子 的费用 (id,amount,date,userid)。现在我试图创建一个收入总和,一年金额总和的视图。它也必须是GROUPED by yearuserid

所以新表(视图)必须有收入,费用,年份的总和。现在我被困在这段代码上了。

SELECT
    id,
    i.Prihod,
    e.Rashod,
    YEAR
    YEAR(COALESCE(e.god, i.godi))) AS Godina , 
    users_id
FROM
    (
        SELECT 
            sum(insum) as 'Prihod',
            YEAR(datum) as 'Godi',
            users_id 
        FROM
        GROUP BY users_id
    ) as i
FULL OUTER JOIN
(
    SELECT 
        sum(amount) as 'Rashod',
        YEAR(datum) as 'God',
        users_id
    FROM expense
    GROUP BY users_id

) as e

1 个答案:

答案 0 :(得分:0)

这是结构化查询语言的结构化部分的工作。从三个子查询(虚拟表)开始。

第一:年份和用户的列表。你需要这个,因为MySQL没有FULL OUTER JOIN能力。如果您正确地编写此查询,则每个用户每年都会包含一行。

              SELECT DISTINCT YEAR(datum) Godi, users_id FROM income
              UNION
              SELECT DISTINCT YEAR(datum) Godi, users_id FROM expense

其次,按年份和用户汇总收入。

               SELECT sum(insum) as Prihod,
                      YEAR(datum) as Godi,
                      users_id 
                 FROM income
                GROUP BY YEAR(datum), users_id

第三,按年和用户划分的类似费用

               SELECT sum(amount) as Rashod,
                      YEAR(datum) as God,
                      users_id 
                 FROM expense
                GROUP BY YEAR(datum), users_id

接下来,单独测试这些子查询,独立测试,以确保您获得预期的结果。

最后,将它们连接在一起就像它们是表格一样,

SELECT yr.users_id, yr.Godi, inc.Prihod, exp.Rashod
  FROM (
              SELECT DISTINCT YEAR(datum) Godi, users_id FROM income
              UNION
              SELECT DISTINCT YEAR(datum) Godi, users_id FROM expense
       ) yr
  LEFT JOIN (
               SELECT sum(insum) as Prihod,
                      YEAR(datum) as Godi,
                      users_id 
                 FROM income
                GROUP BY YEAR(datum), users_id
       ) inc ON yr.users_id = inc.users_id AND yr.Godi = inc.Godi 
  LEFT JOIN (
               SELECT sum(amount) as Rashod,
                      YEAR(datum) as God,
                      users_id 
                 FROM expense
                GROUP BY YEAR(datum), users_id
       ) exp ON yr.users_id = exp.users_id AND yr.Godi = exp.God 

这里的查询模式是开发三个子查询。第一个确定最终结果集中的行数,因为它为每个所需行包含一行。对于最终结果集中所需的每一行,第二个和第三个查询都有一行或零行。然后你加入他们。