用于查找表中多次出现的列值的SQL查询?

时间:2016-03-01 06:42:23

标签: sql sql-server database sql-server-2008

我的SQL查询面临问题:

场景:我需要生成多个讲座时间段的计数,其中包括教师,科目和教师。讲座日期相同。请参考下面所需的输出部分和SQL查询。请让我知道可以对现有查询进行哪些更改。

表:“SCHOOL_RECORDS”

FACULTY_NAME   SUBJECT   LECTURE_DATE   LECTURE_TIME_SLOT
----------------------------------------------------------
Alex           Biology   10/01/2015     0900 - 1200
Alex           Biology   10/01/2015     0900 - 1200
Alex           Biology   10/01/2015     0900 - 1200
Lisa           Chemistry 10/01/2015     0900 - 1200
Lisa           Chemistry 10/01/2015     1700 - 2200
Lisa           Chemistry 10/01/2015     1700 - 2200
Lisa           Chemistry 11/01/2015     0900 - 1200

期望的输出:

FACULTY_NAME   SUBJECT   LECTURE_DATE   LECTURE_TIME_SLOT Count_Of_TimeSlots
----------------------------------------------------------------------------
Alex           Biology   10/01/2015     0900 - 1200       3
Lisa           Chemistry 10/01/2015     0900 - 1200       1
Lisa           Chemistry 10/01/2015     1700 - 2200       2
Lisa           Chemistry 11/01/2015     0900 - 1200       1

当前SQL查询:

Select a.FACULTY_NAME, 
       a.SUBJECT, 
       a.LECTURE_DATE, 
       a.LECTURE_TIME_SLOT, 
       b.Count_Of_TimeSlots

from SCHOOL_RECORDS a
inner join(
           select FACULTY_NAME, SUBJECT, LECTURE_DATE, LECTURE_TIME_SLOT,       
           count(LECTURE_TIME_SLOT) as Count_Of_TimeSlots 
           from SCHOOL_RECORDS 
           group by LECTURE_TIME_SLOT
          ) b 
on a.FACULTY_NAME = b.FACULTY_NAME and a.SUBJECT = b.SUBJECT and      
a.LECTURE_DATE = b.LECTURE_DATE and a.LECTURE_TIME_SLOT =   
b.LECTURE_TIME_SLOT;

提前致谢!

2 个答案:

答案 0 :(得分:2)

试试这个..

 select FACULTY_NAME, SUBJECT, LECTURE_DATE, LECTURE_TIME_SLOT,       
       count(LECTURE_TIME_SLOT) as Count_Of_TimeSlots 
       from SCHOOL_RECORDS 
       group by FACULTY_NAME, SUBJECT, LECTURE_DATE,LECTURE_TIME_SLOT

答案 1 :(得分:1)

SELECT FACULTY_NAME, SUBJECT, LECTURE_DATE, LECTURE_TIME_SLOT, 
       COUNT(*) AS Count_Of_TimeSlots
FROM   SCHOOL_RECORDS
GROUP BY FACULTY_NAME, SUBJECT, LECTURE_DATE, LECTURE_TIME_SLOT