MySQL 合并两个不相关表的结果

MySQL combine results of two unrelated tables

我正在尝试将两个查询结果合并为一个: 查询 1 和结果:

    SELECT MONTHNAME(tblFeesPaid.Pay_Date) AS 'Month', 
            SUM(tblFeesPaid.Fees_Paid) As 'Total Fees' 
    FROM tblFeesPaid 
        INNER JOIN tblFeesStructure ON tblFeesPaid.FID=tblFeesStructure.ID 
    WHERE Year(tblFeesPaid.Pay_Date)=2022 
    GROUP BY month(tblFeesPaid.Pay_Date);

结果

    Month    Total Fees 
    January  162000.00
    February 69000.00
    March    146926.00

查询 2 和结果

    SELECT MONTHNAME(tblTransFeesPaid.Pay_Date) AS 'Month', 
            SUM(tblTransFeesPaid.TransFee_Paid) As 'Transport Fees' 
    FROM tblTransFeesPaid 
        INNER JOIN tbltransfeesstructure ON tblTransFeesPaid.TransFID=tbltransfeesstructure.ID 
    WHERE Year(tblTransFeesPaid.Pay_Date)=2022 
    GROUP BY month(tblTransFeesPaid.Pay_Date);

结果

    Month Transport Fees
    March 7000.00

有人可以帮助我使用正确的语法来实现如下结果:

预期结果:

 Month    Total Fees  Transport Fees
 January  162000.00
 February 69000.00
 March    146926.00   7000.00
SELECT Z.Month, sum(Z.TotalFees) As 'Total Fees', sum(Z.TransportFees) As 'Transport Fees'
FROM
(
SELECT MONTHNAME(tblFeesPaid.Pay_Date) AS 'Month',
       SUM(tblFeesPaid.Fees_Paid) As 'TotalFees',
       0 As 'TransportFees'
FROM tblFeesPaid 
INNER JOIN tblFeesStructure ON tblFeesPaid.FID=tblFeesStructure.ID 
WHERE Year(tblFeesPaid.Pay_Date)=2022 
GROUP BY month(tblFeesPaid.Pay_Date)
UNION
SELECT MONTHNAME(tblTransFeesPaid.Pay_Date) AS 'Month',
       0 As 'TotalFees',
       SUM(tblTransFeesPaid.TransFee_Paid) As 'TransportFees' 
FROM tblTransFeesPaid 
        INNER JOIN tbltransfeesstructure ON tblTransFeesPaid.TransFID=tbltransfeesstructure.ID 
    WHERE Year(tblTransFeesPaid.Pay_Date)=2022 
    GROUP BY month(tblTransFeesPaid.Pay_Date)) Z
GROUP BY Z.Month;

首先,确保两个查询 return 列数相同(将 0 作为运输费用添加到第一个查询,并在第二个查询中添加 0 作为总费用);

然后,您将查询联合起来,得到一个大结果集。

之后按月分组,得到MAX(Total Fees)和MAX(Transport Fees)。

这样的东西行得通吗?

    SELECT Month, MAX(`Total Fees`), MAX(`Transport Fees`) FROM (

    (
        SELECT MONTHNAME(tblFeesPaid.Pay_Date) AS 'Month', 
                SUM(tblFeesPaid.Fees_Paid) As 'Total Fees',
                0 AS 'Transport Fees'
        FROM tblFeesPaid 
        INNER JOIN tblFeesStructure ON tblFeesPaid.FID=tblFeesStructure.ID 
        WHERE Year(tblFeesPaid.Pay_Date)=2022 
        GROUP BY month(tblFeesPaid.Pay_Date)
    ) t1

    UNION

    (
        SELECT MONTHNAME(tblTransFeesPaid.Pay_Date) AS 'Month', 
                0 AS 'Total Fees',
                SUM(tblTransFeesPaid.TransFee_Paid) As 'Transport Fees' 
        FROM tblTransFeesPaid 
        INNER JOIN tbltransfeesstructure ON tblTransFeesPaid.TransFID=tbltransfeesstructure.ID 
        WHERE Year(tblTransFeesPaid.Pay_Date)=2022 
        GROUP BY month(tblTransFeesPaid.Pay_Date)
    ) t2

  ) t3

  GROUP BY Month;