我有一个数据库表(大约10000多行),上面有这样的数据。
tags_id tag_name contact date_applied
1 happy 12 2019-04-01
2 sad 67 2019-04-01
1 happy 96 2019-04-01
3 angry 56 2019-04-02
2 happy 43 2019-04-02
现在我需要这张桌子看起来像这样。
date_applied happy sad angry
2019-04-01 2 1 0
2019-04-02 1 0 1
如何在Laravel / PHP中实现这一目标?我需要将其保存到另一个数据库表或文件中。
答案 0 :(得分:3)
尝试以下查询。
DB::table('table_name')
->select(DB::raw("
sum( case when tag_name = 'happy' then 1 else 0 end) as happy
,sum( case when tag_name = 'sad' then 1 else 0 end) as sad
,sum( case when tag_name = 'angry' then 1 else 0 end) as angry
"), 'date_applied')
->groupBy('date_applied');
或者您可以使用直接查询
select date_applied
,sum( case when tag_name = 'happy' then 1 else 0 end) as happy
,sum( case when tag_name = 'sad' then 1 else 0 end) as sad
,sum( case when tag_name = 'angry' then 1 else 0 end) as angry
from table
group by date_applied
对于动态代码,
$tags = Tag::all();
$selectQuery = '';
foreach($tags as $tag){
$selectQuery.="sum( case when tag_name = '".$tag->tag_name."' then 1 else 0 end) as ".$tag->tag_name.",";
}
DB::table('table_name')
->select(DB::raw($selectQuery."date_applied")
->groupBy('date_applied')