我正在尝试在Laravel 4.2中编写一个子查询,从子查询中减去数据,然后构建具有必要年龄段的table1,但我无法做到正确。
查询是这样的:
$var1= DB::table('table1')
->select(DB::raw("COUNT(*), CASE
WHEN age >=0 AND age <=20 THEN '0-20'
WHEN age >=21 AND age <=24 THEN '21-24'
WHEN age >=25 AND age <=29 THEN '25-29'
WHEN age >=30 AND age <=34 THEN '30-34'
WHEN age >=35 AND age <=39 THEN '35-39'
WHEN age >=40 AND age <=44 THEN '40-44'
WHEN age >=45 AND age <=49 THEN '45-49'
WHEN age >=50 AND age <=54 THEN '50-54'
WHEN age >=55 AND age <=59 THEN '55-59'
WHEN age >=60 AND age <=64 THEN '60-64'
WHEN age >=65 THEN 65+
END AS age"),
function ($query){
$query->select(DB::raw("( SELECT DATE_FORMAT(NOW(),'%Y') - DATE_FORMAT(birthday,'%Y') - (DATE_FORMAT(NOW(), '00-%m-%d') <
DATE_FORMAT(birthday, '00-%m-%d')) AS age FROM ...
) AS table1"));
})
->groupBy('age')
->get();
答案 0 :(得分:0)
好的,我使用此链接http://laravel.io/forum/12-23-2015-subquery-in-laravel-eloquent-or-query-builder解决了这个问题,并相应地构建了我的查询,其中table1不是DB中的真实表,而是从子查询创建的。这是代码:
$ageband = DB::table('table1')
->select(DB::raw("COUNT(*),
CASE
WHEN age >=0 AND age <=20 THEN '0-20'
WHEN age >=21 AND age <=24 THEN '21-24'
WHEN age >=25 AND age <=29 THEN '25-29'
WHEN age >=30 AND age <=34 THEN '30-34'
WHEN age >=35 AND age <=39 THEN '35-39'
WHEN age >=40 AND age <=44 THEN '40-44'
WHEN age >=45 AND age <=49 THEN '45-49'
WHEN age >=50 AND age <=54 THEN '50-54'
WHEN age >=55 AND age <=59 THEN '55-59'
WHEN age >=60 AND age <=64 THEN '60-64'
WHEN age >=65 THEN '65+'
END AS ageband"))
->from(DB::raw("( SELECT DATE_FORMAT(NOW(),'%Y') - DATE_FORMAT(birthday,'%Y') - (DATE_FORMAT(NOW(), '00-%m-%d') <
DATE_FORMAT(birthday, '00-%m-%d')) AS age FROM health_clients
) as table1"))
->groupBy('ageband')
->get();