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

时间:2017-08-14 05:12:43

标签: eloquent laravel-5.4 laravel-eloquent

我有两个查询应该是union(有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

1 个答案:

答案 0 :(得分:0)

这里不需要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代码或多或少会以原始形式提供上述查询。