2017-07-24 61 views
0

有一個表,如下組通過,獲得只有一個數據集和多個數據集

StudentID Name Subject 
1   AAA Computers 
2   BBB Computers 
2   BBB Electronics 
3   CCC Electronics 

我要加載這個數據,到兩個表如下 OnlyOneSubject表

StudentID Name Subject 
1   AAA Computers 
3   CCC Electronics 

MoreThanOneSubject表

StudentID Name Subject 
2   BBB Computers 
2   BBB Electronics 

我的SQL如下,不知道如何提取數據這下面的查詢。

SELECT *,row_number() over(partition by Name order by Subject) FROM 
STUDENTS 
+2

但它是這麼多,在一個表更好。你爲什麼要分開數據? –

+0

我的問題不完全是這樣,它是相似的,一旦我進入這個多個科目種類,然後我必須應用一些清理規則,並使其只有一行,並將其結合到第一個數據集。 –

回答

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 
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) 

但我真的只能用這個返回結果...不需要劃分一張你必須不斷更新的表格。

相關問題