基本上,我需要显示报告,我需要提供一些基于城市ID和邮政编码的细节。
所以,如果cityId为空,postCode为空,那么这些记录的计数应该在data1下。
同样地,
-当cityId在(123456)中时,这些记录的计数应该在“data2”中
-当cityId进入(789999)时,则为“data3”
-当cityId在(111222)时,则为“data4”
-其他“数据5”
我有两个问题:
将此sql转换为laravel雄辩/querybuilder方式。
最后提到的条件
将(cityId不为空且cityId不在(12345678999111222)中的情况)计数为“data5”
来自客户
")
必须是以上条件的另一部分。
我试过了,但没有达到预期的效果

$result = Customer::select(Customer::raw("SELECT
    COUNT(CASE WHEN cityId IS NULL AND postCode IS NULL then 1 ELSE NULL END) as \"data1\",
    COUNT(CASE WHEN cityId IN (123, 456) then 1 ELSE NULL END) as \"data2\",
    COUNT(CASE WHEN cityId IN (789,999) then 1 ELSE NULL END) as \"data3\",
    COUNT(CASE WHEN cityId IN (111, 222) then 1 ELSE NULL END) as \"data4\",
    COUNT(CASE WHEN cityId IS NOT NULL AND cityId NOT IN (123, 456, 789, 999, 111, 222) then 1 ELSE NULL END ) as \"data5\"
from trial
        "))->get();

预期结果:
数据1:7
数据2:5
数据3:12
数据4:10
数据5:1

最佳答案

目前,我有一个替代的解决方案,我的问题提到,不知怎么解决我的第一个问题。
还在找第二个问题。

DB::table('customers')
        ->select(
            DB::raw('COUNT(CASE WHEN cityId IS NULL AND postCode IS NULL then 1 ELSE NULL END) as "data1",
                    COUNT(CASE WHEN cityId IN (123, 456) then 1 ELSE NULL END) as "data2",
                    COUNT(CASE WHEN cityId IN (789,999) then 1 ELSE NULL END) as "data3",
                    COUNT(CASE WHEN cityId IN (4965,4959) then 1 ELSE NULL END) as "data4",
                    COUNT(CASE WHEN cityId IS NOT NULL AND cityId NOT IN (123, 456, 789, 999, 111, 222) then 1 ELSE NULl END ) as "data5"')
        )->get();

09-11 20:40