我试图显示收集的,通过的,失败的和已发布的同名血统表条目的数量。
我有一张这样的表
Blood Collection
--------------------------------------
id BloodComponent Remarks
1 Whole Blood Passed
2 Whole Blood Failed
3 Whole Blood Released
4 Platelet Passed
5 Platelet Released
6 Plasma Failed
7 Plasma Released
我希望输出类似于:
Name Collected Passed Failed Released
-------------------------------------------------------------
Whole Blood 3 1 1 1
Platelet 2 1 0 1
Plasma 2 0 1 1
我使用laravel作为框架...
答案 0 :(得分:1)
您可以通过pivot
表格查询执行此操作:
SELECT
BloodComponent AS name, count(*) AS Collected,
sum(if(Remarks= 'Passed', 1, 0)) AS 'Passed',
sum(if(Remarks= 'Failed', 1, 0)) AS 'Failed',
sum(if(Remarks= 'Released', 1, 0)) AS 'Released'
FROM bloodcollection
GROUP BY BloodComponent ;
您可以使用selectRaw
编写自定义选择语句,在laravel中执行此操作:
DB::table('bloodcollection')
->selectRaw("SELECT
BloodComponent AS name, count(*) AS Collected,
sum(if(Remarks= 'Passed', 1, 0)) AS 'Passed',
sum(if(Remarks= 'Failed', 1, 0)) AS 'Failed',
sum(if(Remarks= 'Released', 1, 0)) AS 'Released'")
->groupBy("BloodComponent")
->get();