提问者:小点点

我怎么能执行一个sql查询,其中包含计数(id_field)和组(f_1,f_2)雄辩?


我正在尝试执行下一个SQL查询:

SELECT  sex, recuperated, count(case_id) as total_cases
FROM api.patients
GROUP BY recuperated, sex
ORDER BY total_cases DESC;

返回:

'41523', 'ANTIOQUIA', 'MEDELLIN'
'6066', 'ANTIOQUIA', 'BELLO'
'6056', 'AMAZONAS', 'LETICIA'
'3855', 'ANTIOQUIA', 'ITAGUI'

首先是雄辩的:

$query = Patient::query();    
$statistics[0] = $query
->select("sex", "recuperated", "count (case_id) as total_cases")
->orderBy("total_cases","desc")
->groupBy("recuperated")
->get();

它返回:

照明\数据库\查询异常SQLSTATE[42S22]:未找到列: 1054未知列'total_cases'在'顺序子句'(SQL:选择计数(*)作为聚合从<代码>患者组按<代码>休养,<代码>性按<代码>顺序>total_casesdesc)

雄辩的第二位:

$query = Patient::query();    
$statistics[0] = $query
->select('sex','recuperated',DB::raw('count(case_id) AS   total_cases'))
        ->orderBy('total_cases','DESC')
        ->groupBy('recuperated')
        ->get();

共1个答案

匿名用户

这现在对我有用。

    $statistics[0] = $query
    ->select(DB::raw('count(*) as patient_count, state'))
    ->orderBy('patient_count')
    ->groupBy('state')
    ->get();

答复是:

[
{"patient_count":18,"state":"Grave"}
{"patient_count":30,"state":"Moderado"},
{"patient_count":472,"state":"N\/A"},
{"patient_count":2110,"state":"Fallecido"},
{"patient_count":76137,"state":"Leve"}
]

这是它看起来的图片:图片网址

我没有使用分页,我只是试图用信息来建立统计数据。