有一张表格如下
StudentID Name Subject
1 AAA Computers
2 BBB Computers
2 BBB Electronics
3 CCC Electronics
我想将这些数据加载到两个表中,如下所示 OnlyOneSubject Table
StudentID Name Subject
1 AAA Computers
3 CCC Electronics
MoreThanOneSubject Table
StudentID Name Subject
2 BBB Computers
2 BBB Electronics
我的sql如下,不确定如何从以下查询中提取数据。
SELECT *,row_number() over(partition by Name order by Subject) FROM
STUDENTS
答案 0 :(得分:2)
第一个......
select *
from table
where StudentID in (select StudentID from table group by StudentID having count(*) = 1)
第二个......
select *
from table
where StudentID in (select StudentID from table group by StudentID having count(*) > 1)
但我真的只使用它来返回结果......不需要划分一个你必须经常更新的表。
答案 1 :(得分:1)
你可以使用:
WITH STUDENTS(StudentID,Name,Subject)AS(
SELECT 1,'AAA','Computers' UNION ALL
SELECT 2,'BBB','Computers' UNION ALL
SELECT 2,'BBB','Electronics' UNION ALL
SELECT 3,'CCC','Electronics'
)
select * from (
SELECT *,count(0) over(partition by Name) as cnt FROM STUDENTS
) as t where cnt=1 ---or cnt>1 for MoreThanOneSubject
StudentID Name Subject cnt 1 AAA Computers 1 3 CCC Electronics 1