我需要按行计算课程数。这意味着将课程后的大学名称添加到一行
College_name course_name1 course_name2 course_name3 course_name4
----------------------------------------------------------------------------
ABC College computer bca cdb
xbc college acvb bca ads abc
xdb college cgd ghdg
vvv college anb abd bca
我在SQL中需要这样的结果格式。我需要计算课程数:
College_name course_count
------------------------------
ABC College 3
xbc college 4
xdb college 2
vvv college 3
答案 0 :(得分:0)
您可以使用union all
:
select College_name, count(Course) as course_count
from (select College_name, course_name1 as Course
from table
union all
select College_name, course_name2
from table
. . .
) t
group by College_name;
答案 1 :(得分:0)
您的数据结构非常差。您应该有一个CollegeClasses
表,每个学院和每个班级一行。那么这将是简单的聚合。
相反,您可以做一个大的表情来添加内容:
select college_name,
( (case when course_name1 is not null then 1 else 0 end) +
(case when course_name2 is not null then 1 else 0 end) +
(case when course_name3 is not null then 1 else 0 end) +
(case when course_name4 is not null then 1 else 0 end)
) as num_courses
from t;
答案 2 :(得分:0)
您可以结合使用取消透视和分组:
SELECT
College_name,
COUNT(course_name) AS course_count
FROM
(
SELECT
College_name,
course_name
FROM
table AS t
UNPIVOT
(
course_name for courses in (course_name1, course_name2, course_name3, course_name4)
) AS unpiv
) AS d
GROUP BY
College_name
答案 3 :(得分:0)
如果您使用的是UNPIVOT
,则可以使用sql-server
SELECT College_name, COUNT(*) course_count
FROM MyTable
UNPIVOT( V FOR C IN (course_name1, course_name2, course_name3, course_name4)) UNPVT
GROUP BY College_name
答案 4 :(得分:-1)
您将通过以下代码获取课程计数,如果适合您,请标记正确答案
select (course_name1 + course_name2 + course_name3 + course_name4 ) as course_count from (select case when course_name1 is not null then 1 else 0 end as course_name1, case when
course_name2 is not null then 1 else 0 end as course_name2,
case when course_name3 is not null then 1 else 0 end as course_name3,case when
course_name4 is not null then 1 else 0 end as course_name4
from desktopschduleremark ) as tst