SQL查询以查找表中列值多次出现的计数?
Posted
技术标签:
【中文标题】SQL查询以查找表中列值多次出现的计数?【英文标题】:SQL query to find count of multiple occurrences of column values from a table? 【发布时间】:2016-03-01 06:42:23 【问题描述】:我的 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;
提前致谢!
【问题讨论】:
【参考方案1】:试试这个..
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
【讨论】:
您需要在 GROUP BY 中使用 LECTURE_TIME_SLOT 哎呀..编辑查询...谢谢@Squirrel【参考方案2】: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
【讨论】:
以上是关于SQL查询以查找表中列值多次出现的计数?的主要内容,如果未能解决你的问题,请参考以下文章