一个表SQL的不同列中的COUNT值

时间:2016-11-27 22:30:12

标签: sql oracle

例如,我的表有数据 - 10名志愿者。 有两种类型的志愿者 - 学生和工作人员。 如何使用此视图在一个表中插入几列:

COUNT(Volunteer_id),COUNT(Volunteer_id)在哪里Volunteer_type ='学生', COUNT(Volunteer_id在哪里Volunteer_type ='员工'

SELECT COUNT(Volunteer_id) AS "TOTAL VOLUNTEERS"
from volunteer
UNION
SELECT COUNT(Volunteer_id) AS "TOTAL VOLUNTEERS"
from volunteer
WHERE Volunteer_type = 'Staff'
UNION
SELECT COUNT(Volunteer_id) AS "TOTAL VOLUNTEERS"
from volunteer
WHERE Volunteer_type = 'Student'

此语句现在表示为行,但我想将它们设为列

3 个答案:

答案 0 :(得分:5)

使用条件聚合:

it "updates the requested" do
    some_object = SomeObject.create! valid_attributes
    put :update, {id: some_object.to_param, some_object: new_attributes}, session: valid_session
    some_object.reload
    skip("Add assertions for updated state")
end

答案 1 :(得分:0)

试试这个:

select
  sum(t.x_all) cnt_all,
  sum(t.x_staff) cnt_staff,
  sum(t.x_student) cnt_student
from (
  select
    1 x_all,
    case when v.volunteer_type = 'Staff' then 1 else 0 end x_staff,
    case when v.volunteer_type = 'Student' then 1 else 0 end x_student
  from volunteer v
) t

答案 2 :(得分:-1)

DECLARE @volunteer TABLE 
(Volunteer_id int 
,Volunteer_type varchar(50) )

INSERT INTO @volunteer  VALUES (1,'Staff')
INSERT INTO @volunteer  VALUES (1,'Staff')
INSERT INTO @volunteer  VALUES (1,'Staff')

INSERT INTO @volunteer  VALUES (1,'Student')
INSERT INTO @volunteer  VALUES (1,'Student')
INSERT INTO @volunteer  VALUES (1,'Student')


SELECT COUNT(Volunteer_id) AS "TOTAL VOLUNTEERS"
       ,(
           SELECT  COUNT(tb1.Volunteer_id) AS "TOTAL VOLUNTEERS"
           FROM   @volunteer AS tb1
           WHERE  tb1.Volunteer_id = tb.Volunteer_id
             AND  tb1.Volunteer_type = 'Staff'


       )
       ,(
           SELECT COUNT(volunteer_Student.Volunteer_id) AS "TOTAL VOLUNTEERS"
           FROM   @volunteer AS volunteer_Student
           WHERE  volunteer_Student.Volunteer_id = tb.Volunteer_id
             AND  volunteer_Student.Volunteer_type = 'Student'
       )
FROM   @volunteer tb
GROUP BY tb.Volunteer_id