sql Count语句

时间:2012-10-11 08:35:54

标签: sql oracle count group-by

我有一个表名为JOB_Details,数据显示如下:

Age           Department:IT         
              Male     Female 
30yrs         5          1              
30-34yrs      3          2              
35-39yrs      4          4              
40-49yrs      2          3              
50-54yrs      1          0              

,输出结果如下:

Age           Department:IT          Total
              Male     Female 
30yrs         5          1              6
30-34yrs      3          2              5
35-39yrs      4          4              8
40-49yrs      2          3              5
50-54yrs      1          0              1
Total         15         10             25

我该怎么办?因为当使用计数和按功能分组时,结果结果将不是我想要的。有人可以介意给我一些建议吗?为了您的信息,我使用Oracle。

2 个答案:

答案 0 :(得分:2)

SELECT AGE, MALE, FEMALE, SUM(MALE + FEMALE) AS TOTAL
FROM JOB_DETAILS
GROUP BY AGE

编辑:

如果您想要运行总计,则必须使用ROLLUP(SQL Server)

SELECT AGE, MALE, FEMALE, SUM(MALE + FEMALE) AS TOTAL
FROM JOB_DETAILS
GROUP BY AGE
WITH ROLLUP 

答案 1 :(得分:0)

尝试使用union all,如下所示:

SELECT age, Male, Female, nvl(Male,0) + nvl(Female,0) as total
FROM JOB_Details 
union all
SELECT 'TOTAL', sum(Male), sum(Female), sum(nvl(Male,0) + nvl(Female,0))
FROM JOB_Details 

有了观点:

create view vJOB_Details 
SELECT (CASE WHEN age='30' THEN Count(EMPLID) 
             WHEN age='34' THEN Count(EMPLID) 
             WHEN age='39' THEN Count(EMPLID) 
             WHEN age='49' THEN Count(EMPLID) 
             WHEN age='54' THEN Count(EMPLID) 
             ELSE NULL 
        END) TOTAL_COLUMN ,
        (CASE WHEN GENDER1='M' THEN Count(EMPLID) 
              WHEN GENDER1='F' THEN Count(EMPLID) 
              ELSE NULL 
         END) TOTAL_GENDER 
FROM job_details 
GROUP BY age,GENDER 

SELECT age, Male, Female, nvl(Male,0) + nvl(Female,0) as total
FROM vJOB_Details 
union all
SELECT 'TOTAL', sum(Male), sum(Female), sum(nvl(Male,0) + nvl(Female,0))
FROM vJOB_Details;