加入 2 个表给出空结果

Joining 2 Tables Gives Null Result

我想合并这两个表。

销售额Table

费用Table

这是我将它们结合起来的代码:

SELECT sl.month, sl.sumnet, ex.sumexp, (sl.sumnet-ex.sumexp) AS profit
FROM
    (SELECT date, DATE_FORMAT(date,'%m%Y') AS date_id, 
            DATE_FORMAT(date,'%b') AS month, 
            YEAR(date) AS year, SUM(net_sales) AS sumnet 
    FROM sales 
    GROUP BY month) sl
LEFT JOIN 
        (SELECT date, DATE_FORMAT(date,'%m%Y') AS date_id, 
                DATE_FORMAT(date,'%b') AS month, 
                YEAR(date) AS year, SUM(total) as sumexp 
        FROM expense 
        GROUP BY month) ex 
    ON sl.date_id = ex.date_id 
WHERE sl.year = '2021'
ORDER BY sl.date_id ASC

我只想显示 2021 年的结果,但 11 月的 sumexpprofit 列显示 NULL(见下文)。我该如何解决?

可能的答案,你一定要注意nulls

select
 s.date_id,
 s.`month` ,
 s.`year` ,
 sum(s.sumnet),
 sum(distinct coalesce(e.sumexp,0)),
 sum(s.sumnet) - sum(distinct coalesce(e.sumexp,0)) 
from sales as s
left join expanse as e on s.date_id = e.date_id and s.`month` = e.`month` and s.`year` = e.`year`
group by date_id, `month` , `year`;

并根据您的需要进行过滤。

尝试

SELECT sl.month, sl.sumnet, ex.sumexp, (sl.sumnet-ex.sumexp) AS profit
FROM
    (SELECT date, DATE_FORMAT(date,'%m%Y') AS date_id, 
            DATE_FORMAT(date,'%b') AS month, 
            YEAR(date) AS year, SUM(net_sales) AS sumnet 
    FROM sales 
    WHERE year='2021'
    GROUP BY month) sl
LEFT JOIN 
        (SELECT date, DATE_FORMAT(date,'%m%Y') AS date_id, 
                DATE_FORMAT(date,'%b') AS month, 
                YEAR(date) AS year, SUM(total) as sumexp 
        FROM expense 
        WHERE year='2021'
        GROUP BY month) ex 
    ON sl.date_id = ex.date_id 
ORDER BY sl.date_id ASC

您只过滤了一个 table 的年份,因此另一个显示具有多个值的 null。