我的桌子名为“出勤”,如下所示:
Sno SecurityGroup SecurityName Designation AttendanceStatus
----------------------------------------------------------------
1 JJ Ram officer present
2 JJ Raja Guards Present
3 JJ Rani LadyGuards Present
4 JJ Ramu officer present
我需要输出作为每个指定中存在的证券数量的计数如下:
SecutityGroup Officer Guards LadyGuards
-----------------------------------------
JJ 2 1 1
有人可以帮我写一个查询来获得这个输出吗?
答案 0 :(得分:7)
select SecurityGroup,
sum(case when Designation = 'officer' then 1 end) as Officer,
sum(case when Designation = 'Guards' then 1 end) as Guards,
sum(case when Designation = 'LadyGuards' then 1 end) as LadyGuards
from Attendance
group by SecurityGroup
或者,如果您可以在行中获取信息,则可以执行以下操作:
select SecurityGroup, Designation, count(*) as Count
from Attendance
group by SecurityGroup, Designation
显然第二种方法是优选的,因为它不那么脆弱,并且如果在没有任何修改的情况下添加更多Designations
,它将起作用。
答案 1 :(得分:2)
这也可以使用PIVOT完成,具体取决于您的数据库:
SELECT SecurityGroup, SUM([officer]) AS Officers, SUM([Guards]) AS Guards, SUM([LadyGuards]) AS LadyGuards
FROM Attendance
PIVOT
(
COUNT(Sno)
FOR Designation IN ([officer], [Guards], [LadyGuards])
) as pvt
WHERE AttendanceStatus = 'Present'
GROUP BY SecurityGroup
如果您希望根据表中的内容动态生成列列表,则会变得更难,但这样可以避免需要大量子查询。
答案 2 :(得分:0)
select distinct SecurityGroup,
select sum(*) from Attendance where designation = 'officer') as Officer,
select sum(*) from Attendance where designation = 'Guards') as Guards,
select sum(*) from Attendance where designation = 'LadyGuards') as LadyGuards
from Attendance
答案 3 :(得分:0)
您可以使用子查询来完成此任务:
SELECT
SecurityGroup,
(SELECT COUNT(*) FROM `Attendance` WHERE `Designation` = "officer") AS `Officer`,
(SELECT COUNT(*) FROM `Attendance` WHERE `Designation` = "Guards") AS `Guards`,
(SELECT COUNT(*) FROM `Attendance` WHERE `Designation` = "LadyGuards") AS `LadyGuards`
FROM `Attendance`
WHERE `SecurityGroup` = "JJ"
我实际上没有测试过这个查询,因为我只想和你分享这个概念。
另外请注意,这不是完成所需工作的最快方法,但我相信这是最简单的方法。
我希望这适合你。
答案 4 :(得分:0)
我在SQL中尝试使用PIVOT但是我无法获得计数值.. 以下是我试过的代码:
select SecurityGroup,Officer,Guards,LadyGuards from
(select SecurityGroup,rDesignation from Attendance
where SecurityGroup='jj') up
PIVOT (count(Designation) for Designation IN
(Officer,Guards,LadyGuards)) as pvt
当我执行此查询时,我明白了 SecurityGroup,官,逆天,LadyGuards JJ,0,0,0
而不是, SecurityGroup,官,逆天,LadyGuards JJ,2,1,1