我试图弄清楚一个学生在大学生涯中换过专业的次数。
Create Table Taco
( s_id varchar(9),
s_year int,
s_major varchar(50))
Insert INTO Taco
Values (123456789, 2018, 'PSYCHOLOGY'),
(123456789, 2016, 'GENERAL EDUCATION'),
(123456789, 2017, 'PSYCHOLOGY'),
(987654321, 2018, 'FILM'),
(987654321, 2017, 'ANTHROPOLOGY'),
(654789123, 2018, 'BIOLOGY'),
(654789123, 2017, 'BIOLOGY'),
(987654321, 2015, 'COMPUTER SCIENCE')
我期待结果:
s_id changes
123456789 2
987654321 3
654789123 1
我该怎么写?
答案 0 :(得分:3)
使用Count
和GROUP BY
SELECT s_id,count(s_id) 'changes'
FROM Taco
group by s_id
sqlfiddle:http://sqlfiddle.com/#!18/2c1d7/2
答案 1 :(得分:1)
要获取实际更改的数量,可以使用LAG
函数来接收组(s_id
)中的最后一个值,并汇总前一个值和当前值之间的所有差异:>
SELECT t.s_id
, SUM(CASE WHEN t.prev_val <> t.s_major OR t.prev_val IS NULL THEN 1 END) as chg_cnt
FROM
(
SELECT s_id
,s_year
, s_major
, LAG(s_major) OVER(PARTITION BY s_id ORDER BY s_year) prev_val
FROM Taco
) as t
GROUP BY s_id
扩展的sqlfiddle代码:http://sqlfiddle.com/#!18/61048/11
答案 2 :(得分:0)
您只需对表中的条目进行计数并减去一个即可确定每个学生的更改量。
SELECT
s_id,
COUNT(s_id) - 1 AS [Amount of changes]
FROM
Taco
GROUP BY
s_id
我还建议将最后一列的类型更改为varchar(50)
或更大的值。
请参见SQL提琴:http://sqlfiddle.com/#!18/59ae2/1