我正在尝试将原始SQL查询转换为雄辩的语句,并且由于连接部分变得相当复杂,因此我正为此而苦苦挣扎。
我已经很了解联接,但是我正在查看文档并努力找出如何转换其余部分。
这是原始查询
SELECT
SUM(CASE WHEN t2.field_2 = 1 THEN 1 ELSE 0 END) AS 'lead',
SUM(CASE WHEN t2.field_2 = 2 THEN 1 ELSE 0 END) AS 'in_review',
SUM(CASE WHEN t2.field_2 = 3 THEN 1 ELSE 0 END) AS 'pre_app_sent',
SUM(CASE WHEN t2.field_2 = 4 THEN 1 ELSE 0 END) AS 'pre_app_back',
SUM(CASE WHEN t2.field_2 = 5 THEN 1 ELSE 0 END) AS 'pre_app_ok',
SUM(CASE WHEN t2.field_2 = 6 THEN 1 ELSE 0 END) AS 'awaiting_kyc',
SUM(CASE WHEN t2.field_2 = 7 THEN 1 ELSE 0 END) AS 'kyc_complete',
SUM(CASE WHEN t2.field_2 = 8 THEN 1 ELSE 0 END) AS 'awaiting_full_app_data',
SUM(CASE WHEN t2.field_2 = 9 THEN 1 ELSE 0 END) AS 'full_app_sent',
SUM(CASE WHEN t2.field_2 = 10 THEN 1 ELSE 0 END) AS 'merchant_live'
FROM leads l
JOIN (SELECT
ae.id,
ae.model_id,
ae.fields,
TRIM(BOTH '"' FROM SUBSTRING_INDEX(SUBSTRING_INDEX(ae.fields,';', 1), ':', -1)) AS field_1,
TRIM(BOTH '"' FROM SUBSTRING_INDEX(SUBSTRING_INDEX(ae.fields,';', 2), ':', -1)) AS field_2,
ae.created_at
FROM action_events ae) t2
ON l.id = t2.model_id
WHERE t2.created_at >= '2019-01-01 00:00:00'
AND t2.created_at <= '2019-01-31 23:59:59'
据我所知,将其转换为雄辩
$query->select(
DB::raw('SUM(CASE WHEN t2.field_2 = 1 THEN 1 ELSE 0 END) AS "lead"'),
DB::raw('SUM(CASE WHEN t2.field_2 = 2 THEN 1 ELSE 0 END) AS "in_review"'),
DB::raw('SUM(CASE WHEN t2.field_2 = 3 THEN 1 ELSE 0 END) AS "pre_app_sent"'),
DB::raw('SUM(CASE WHEN t2.field_2 = 4 THEN 1 ELSE 0 END) AS "pre_app_back"'),
DB::raw('SUM(CASE WHEN t2.field_2 = 5 THEN 1 ELSE 0 END) AS "pre_app_ok"'),
DB::raw('SUM(CASE WHEN t2.field_2 = 6 THEN 1 ELSE 0 END) AS "awaiting_kyc"'),
DB::raw('SUM(CASE WHEN t2.field_2 = 7 THEN 1 ELSE 0 END) AS "kyc_complete"'),
DB::raw('SUM(CASE WHEN t2.field_2 = 8 THEN 1 ELSE 0 END) AS "awaiting_full_app_data"'),
DB::raw('SUM(CASE WHEN t2.field_2 = 9 THEN 1 ELSE 0 END) AS "full_app_sent"'),
DB::raw('SUM(CASE WHEN t2.field_2 = 10 THEN 1 ELSE 0 END) AS "merchant_live"'));