2017-10-22 89 views
0

我是SQL新手,我想找出其值集相同的元素。如何用SQL查找具有相同值的元素

例如,我有錄取的一個表,其中包含學生,當然喜歡:

Student Course 
------- ------ 
Alice OS 
Alice Network 
Bob  OS 
Bob  Network 
Carl Database 
Carl Network 
------------- 
Expected output: Alice, Bob 
Because they are taking the same set of courses 

我要的是找出Alice和Bob,因爲他們正在採取同一套課程。我必須使用光標或類似的東西嗎?謝謝。

+1

請至少以樣本數據正確地發佈您的要求,我們可能很難幫助您解決目前的問題。編輯您的問題,我相信您會得到很多幫助 –

+0

剛剛對排版不好的人抱歉。 – Yiyang

+0

你正在使用哪個數據庫?你的預期結果是什麼? – GurV

回答

0

可以篩選使用WHERE子句和having子句一起找出所有正在一組特定的課程的學生(和組CONCAT它們作爲你的輸出預計):

select group_concat(student) 
from (
    select student 
    from enrolls 
    where course in ('OS', 'Network') 
    group by student 
    having count(distinct course) = 2 
    ) t; 

如果你想發現學生所只招收在兩門課程,這樣做:

select group_concat(student) 
from (
    select student 
    from enrolls 
    group by student 
    having count(
     distinct 
     case when course in ('OS', 'Network') 
     then course end 
     ) = 2 
    and count(distinct course) = 2 
    ) t; 
+0

謝謝你的幫助。 – Yiyang

+0

@Yiyang - 很高興幫助。如果此答案或任何其他人解決了您的問題,請考慮接受/提高這一點。謝謝 – GurV

0

數據製作部:

Declare @StudentCourse table 
(
    StudentName varchar(30), 
    Course varchar(30) 
) 

Insert into @StudentCourse 
select 'Alice','OS' union all 
select 'alice','Network' union all 
select 'Bob','OS' union all 
select 'Bob','NetWork' union all 
select 'Carl','Database' union all 
select 'Carl','Network' 

您可以使用XML路徑功能連接一名學生下的課程。將此結果集存儲在臨時表中。請找到下面的查詢此:

Select StudentName, 
Stuff(
     (
     select ','+ Course from @StudentCourse where StudentName = 
     temp.StudentName for XML path('') 
    ), 
    1,1,'') as Courses into #tempTable 
From (select distinct StudentName from @StudentCourse)temp 

下面查詢中使用以查看結果集:

select * from #tempTable 

現在,你可以用下面的查詢看到學生用同一套課程:

select t1.StudentName, t1.Courses from #tempTable t1 join 
(
    select Courses from #tempTable group by courses having count(1)>1 
) as tmpCourses 
on t1.Courses=tmpCourses.Courses 

我希望這會有所幫助。

相關問題