我正在尝试显示具有相同名称的收集和发布的血液表条目的数量。
我有一张这样的表
Blood Collection
--------------------------------------
id BloodComponent Remarks
1 Whole Blood Collected
2 Platelet Released
3 Plasma Collected
4 Platelet Released
5 Plasma Collected
6 Whole Blood Released
我希望输出类似于:
Name Collected Released
---------------------------------------
Whole Blood 1 1
Platelet 0 2
Plasma 2 0
我使用laravel作为框架...
答案 0 :(得分:3)
当您要求行成为数据列时,您将使用交叉表查询转换行:
SELECT `BloodComponent` AS `Name`,
SUM(IF(`Remarks` = 'Collected', 1, 0)) AS `Collected`,
SUM(IF(`Remarks` = 'Released', 1, 0)) AS `Released`
FROM `BloodCollection`
GROUP BY `BloodComponent`
这是一个informative post,以更详细的方式展示了这些类型的查询。
在Laravel:
DB::table("BloodCollection")
->selectRaw("`BloodComponent` AS `Name`,SUM(IF(`Remarks` = 'Collected', 1, 0)) AS `Collected`,SUM(IF(`Remarks` = 'Released', 1, 0)) AS `Released`")
->groupBy("BloodComponent")
->get();
答案 1 :(得分:1)
在laravel:
$results = DB::table("BloodCollection")
->selectRaw("BloodComponent AS Name,SUM(IF(Remarks = 'Collected', 1, 0)) AS Collected,SUM(IF(Remarks = 'Released', 1, 0)) AS Released")
->groupBy("BloodComponent")
->get();
或者如果您已经拥有BloodCollection
型号:
$results = BloodCollection::selectRaw("BloodComponent AS Name,SUM(IF(Remarks = 'Collected', 1, 0)) AS Collected,SUM(IF(Remarks = 'Released', 1, 0)) AS Released")
->groupBy("BloodComponent")
->get();
然后:
foreach($results as $result){
echo $results->Name . ": ".$results->Collected ." collected, ".$results->Released ." released.";
}