联合两个 SQL 具有同一列的查询(使用 Eloquent )

Union two SQL Queries with one same column ( using Eloquent )

我有两个应该联合的查询(与 laravel eloquent)但是两个查询中都有一个名为 group_date 的重复列,我应该显示其中一个

SELECT
  to_char(CREATE_UTC_DATETIME, 'yyyy-mm-dd') AS group_date,
  COUNT(*)                                   AS successful_transaction
FROM "REPORT_EVENTS"
WHERE "RESULT_CODE" = '0' AND "EVENT_TYPE" = 'BILL'
GROUP BY to_char(CREATE_UTC_DATETIME, 'yyyy-mm-dd')
ORDER BY "GROUP_DATE" DESC

SELECT
  to_char(CREATE_UTC_DATETIME, 'yyyy-mm-dd') AS group_date,
  COUNT(*)                                   AS unsuccessful_transaction
FROM "REPORT_EVENTS"
WHERE "RESULT_CODE" = '1' AND "EVENT_TYPE" = 'BILL'
GROUP BY to_char(CREATE_UTC_DATETIME, 'yyyy-mm-dd')
ORDER BY "GROUP_DATE" DESC

这里不需要 UNION,而是使用条件聚合的单个查询:

SELECT
    TO_CHAR(CREATE_UTC_DATETIME, 'yyyy-mm-dd') AS group_date,
    SUM(CASE WHEN RESULT_CODE = '0' THEN 1 ELSE 0 END) AS successful_transaction,
    SUM(CASE WHEN RESULT_CODE = '1' THEN 1 ELSE 0 END) AS unsuccessful_transaction
FROM "REPORT_EVENTS"
WHERE "EVENT_TYPE" = 'BILL'
GROUP BY TO_CHAR(CREATE_UTC_DATETIME, 'yyyy-mm-dd')
ORDER BY "GROUP_DATE" DESC

我没有在此处提供任何 Eloquent/Laravel 代码,但我相当确定您需要自定义原始查询来处理此问题。因此,您的实际 PHP 代码或多或少只会包含原始形式的上述查询。