需要在一列中计算两个单独的值

时间:2014-10-07 15:01:15

标签: sql sql-server count

我正在尝试将每个唯一ID的两个单独值的总和显示在一行中。我尝试了几条路线,但仍然无法让所有东西都出现在一排。我尝试过几种不同的使用case语句的方法,我也尝试过使用OVER和分区,但是没有用。

到目前为止,这是我的查询:

select distinct ID_NUM, 
  sum(case when isnull(sch.SUBTERM_CDE,0) like '%N' then 1 else 0 end) as 'total_n',
  sum(case when isnull(sch.SUBTERM_CDE,0) like '%T' then 1 else 0 end) as 'total_t'
from STUDENT_CRS_HIST sch
where sch.END_DTE > GETDATE()
group by sch.ID_NUM, sch.SUBTERM_CDE
order by ID_NUM

2 个答案:

答案 0 :(得分:2)

你几乎是对的,但你要按一个额外的栏目进行分组:

SELECT  ID_NUM, 
        SUM(CASE WHEN sch.SUBTERM_CDE LIKE '%N' THEN 1 ELSE 0 END) AS total_n,
        SUM(CASE WHEN sch.SUBTERM_CDE LIKE '%T' THEN 1 ELSE 0 END) AS total_t
FROM STUDENT_CRS_HIST sch
WHERE sch.END_DTE > GETDATE()
GROUP BY sch.ID_NUM -- you shouldn't group by SUBTERM_CDE
ORDER BY ID_NUM

答案 1 :(得分:1)

更改group by以删除SUBTERM_CDE

select ID_NUM, 
       sum(case when sch.SUBTERM_CDE like '%N' then 1 else 0 end) as total_n,
       sum(case when sch.SUBTERM_CDE like '%T' then 1 else 0 end) as total_t
from STUDENT_CRS_HIST sch
where sch.END_DTE > GETDATE()
group by sch.ID_NUM
order by ID_NUM;

另外:

  • distinct不需要且具有误导性。
  • 不应将列别名括在单引号中(仅对字符串和日期常量使用单引号)。
  • NULL的文字是不必要的 - 并且具有误导性。替代值是一个整数,但该字段应该是一个字符串。