MySQL UNION ALL Derived Table with GROUP BY 无效

MySQL UNION ALL Derived Table with GROUP BY Not Working

这几天我一直在摸不着头脑!我在下面进行查询以组合两个子查询并按日期对它们进行分组。第一次查询中导出table returns 50行,而第二次查询returns 2行。

但是如果我 运行 整个事情,它只会 returns 来自 FIRST 查询的 50 行。 并且应该从第二个查询中组合的任何内容根本没有组合到具有相同 GROUP BY 列值的行。

SELECT  tot.payment_date AS "Payment Period",
        tot.total_sales AS "Total Sales"
FROM
    (
        SELECT  DATE_FORMAT(a.payment_dt, "%c/%d/%Y") AS payment_date,
                CAST((SUM(b.ucost * b.qty) + a.shipping_fee) AS DECIMAL(15,2)) AS total_sales
        FROM    tbl_encash_order_sum a
        INNER JOIN tbl_encash_order_det b
            ON a.accid = b.accid AND a.so_no = b.so_no
        WHERE   a.payment_stat = 1
        GROUP BY DATE_FORMAT(a.payment_dt, "%c/%d/%Y")

        UNION ALL

        SELECT  DATE_FORMAT(d.dp_settled_dt, "%c/%d/%Y") AS payment_date,
                SUM(d.order_total) AS total_sales
        FROM    wp_posts c
        INNER JOIN
            (
                SELECT  post_id,
                        MAX(CASE WHEN meta_key = "_payment_status" THEN CAST(meta_value AS SIGNED) END) AS payment_status,
                        MAX(CASE WHEN meta_key = "_order_total" THEN CAST(meta_value AS DECIMAL(15,2)) END) AS order_total,
                        MAX(CASE WHEN meta_key = "_dp_settled_dt" THEN CAST(meta_value AS DATETIME) END) AS dp_settled_dt
                FROM    wp_postmeta
                GROUP BY post_id
            ) d
            ON c.ID = d.post_id
        WHERE c.post_type = "shop_order" AND d.payment_status = 1
        GROUP BY DATE_FORMAT(d.dp_settled_dt, "%c/%d/%Y")
    ) tot
GROUP BY tot.payment_date
ORDER BY tot.payment_date

这里:

SELECT  tot.payment_date AS "Payment Period",
        tot.total_sales AS "Total Sales"

你应该做 SUM(tot.total_sales)。如果没有总和,它将return每个付款日期的总销售额中的任意一个。

您可以通过启用 ONLY_FULL_GROUP_BY sqlmode 使 mysql 给出错误,而不是选择任意数据给 return。