以下是我的SQL查询。我正在谷歌搜索转换Laravel查询生成器,但找不到一个好的解决方案。请帮助我。
SELECT p.WARD AS `Ward`
, (SELECT COUNT(p1.SEX) FROM persons AS p1 WHERE p1.SEX=1 AND p.`WARD`=p1.WARD) AS `Male`
, (SELECT COUNT(p1.SEX) FROM persons AS p1 WHERE p1.SEX=2 AND p.`WARD`=p1.WARD) AS `Female`
, (SELECT COUNT(p1.SEX) FROM persons AS p1 WHERE p1.SEX=3 AND p.`WARD`=p1.WARD) AS `Other`
FROM persons AS p
GROUP BY p.`WARD` ORDER BY p.`WARD` ASC;
答案 0 :(得分:1)
这里您可以仅使用DB :: select('');在laravel中执行原始sql查询。
检查以下内容。希望能解决您的问题。
$data = DB::select('SELECT p.WARD AS `Ward`
, (SELECT COUNT(p1.SEX) FROM persons AS p1 WHERE p1.SEX=1 AND p.`WARD`=p1.WARD) AS `Male`
, (SELECT COUNT(p1.SEX) FROM persons AS p1 WHERE p1.SEX=2 AND p.`WARD`=p1.WARD) AS `Female`
, (SELECT COUNT(p1.SEX) FROM persons AS p1 WHERE p1.SEX=3 AND p.`WARD`=p1.WARD) AS `Other`
FROM persons AS p
GROUP BY p.`WARD` ORDER BY p.`WARD` ASC;');