SQL - 使用Union All和Join计算

时间:2017-07-25 18:02:34

标签: mysql join union-all

我有3个SQL表,每个供应商一个。所有表都有3个相同的列:(id),(花费)和(日期)。 (id)代表产品ID。 (花费)是他们在产品上花了多少钱。和(日期)交易。

感谢stackoverflow,我能够按每个产品(id)的总花费进行排序,包括所有表格。以下是适用的UNION ALL语句:

SELECT id, SUM(spend) as total
                    FROM (
                        SELECT id, spend, date 
                        FROM vendor1 
                        WHERE date BETWEEN '$dateStart' AND '$dateEnd'
                        UNION ALL
                        SELECT id, spend, date 
                        FROM vendor2
                        WHERE date BETWEEN '$dateStart' AND '$dateEnd'
                        UNION ALL
                        SELECT id, spend, date 
                        FROM vendor3
                        WHERE date BETWEEN '$dateStart' AND '$dateEnd'
                    ) as SpendTotal  
                    GROUP BY id 
                    ORDER BY total DESC

现在我想在SQL公式中加入一个新表(revTbl),列出从每个产品(id)中获得的收入。该第4表具有与上述3相同的标记为(id)的列。它也有相同的(日期)列。但是,此表具有名为(rev)的不同列。

我想编写一个按SUM(rev)-SUM(花费)排序的SQL语句。我尝试将它包括在UNION ALL中,但没有运气,在阅读了UNION ALL之后,我明白了为什么。我猜我需要合并一个JOIN语句,但不知道从哪里开始。请帮我写一下正确的SQL语句。

1 个答案:

答案 0 :(得分:0)

您可以创建两个子查询并按ID加入它们。像这样:

Select rev.id, total_rev - rev_total as result from 
      (SELECT id, SUM(rev) as total_rev
                    FROM rev
                    GROUP BY id) as rev
join  (SELECT id, SUM(spend) as spend_total
                    FROM (
                        SELECT id, spend, at 
                        FROM vendor1 
                        UNION ALL
                        SELECT id, spend, at
                        FROM vendor2
                        UNION ALL
                        SELECT id, spend, at
                        FROM vendor3
                    ) as SpendTotal
                    GROUP BY id) as spend on spend.id = rev.id order by result;

为了简单起见,我从你的sql中删除了条件。还改变了" date"列名称为" at"因为我记得日期是sql数据类型。