2017-08-15 177 views
0

下面的行和列的不同值組合是數據的形式我現在所擁有的從SQL查詢:如何多行,合併單元格與整個使用SQL

ID Name Nationality Institution Degree Result 
--------------------------------------------- 
1 Brian USA  a   b  c 
1 Brian USA  d   e  f 
1 Brian USA  h   i  j 
2 Faye  UK  y   z  x 
2 Faye  UK  o   p  q 

而且數據在理想情況下被歸類爲如下:

ID Name Nationality  Background 
------------------------------------------------- 
1 Brian  USA   a,b,c; d,e,f; h,i,j 
2 Faye  UK   y,z,x; o,p,q 

我是一名SQL初學者,我非常感謝任何幫助。

下面是我當前的SQL查詢:

select 
    table1.id, 
    table1.lastname, 
    table1.firstname, 
    table1.group, 
    table2.institution, 
    table2.degree, 
    table2.result, 
from 
    table1 
inner join 
    table2 on (table1.id = table2.id) 
where 
    ((table1.startyear = '2017') 
    and (table1.group = 'A')) 

提前非常感謝!

亞倫

+0

MySql的<> MS訪問<> MS SQL服務器 – lad2025

+0

MySQL使用和'GROUP_CONCAT()'爲此,SQL服務器將使用'String_Agg()'如果2017年或'Stuff和FORXML路徑',我不認爲msaccess容易處理這個問題所以每個解決方案都依賴於特定的數據庫。你真的在使用什麼數據庫平臺? concat()將用於組合行中的數據,group_concat()用於XML路徑或string_Agg用於組合行。這種類型已經在SO上被回答了幾次。我們只需要知道RDBMS是什麼,所以我們可以鏈接相應的答案。 – xQbert

+1

我編輯了您的帖子以刪除衝突的標籤。請僅標記您使用的DBMS,因爲響應將是DBMS特定的 – JohnHC

回答

0

可以如下查詢:

Select Id, [Name], Nationality, 
    Background = Stuff((Select '; '+Institution+','+Degree+','+Result from #table1 where id = t.Id for xml path('')),1,2,'') 
from #table1 t 
Group by Id, [Name], Nationality 
+0

感謝您的回覆,但似乎有一個錯誤的背景行 – Aaron

+0

它只適用於SQL Server ...不要緊,如果你使用不同的dbms –

0

因此,使用list()和火鳥(IBExpert)的||字符串連接給我們:

UNTESTED:List()Doc需要2.1版本或更大。 A前SO answer using List()

注意Group是在reserved words list;所以你可能有它使用"逃避firebird

SELECT table1.id 
    , table1.lastname 
    , table1.firstname 
    , table1."group" 
    , List(table2.institution ||','|| 
      table2.degree  ||','|| 
      table2.result,';') as Background 
FROM table1 
INNER JOIN table2 
    ON table1.id = table2.id 
WHERE table1.startyear = '2017' 
    AND table1."group" = 'A' 
GROUP BY table1.id 
     , table1.lastname 
     , table1.firstname 
     , table1."group" 
+0

感謝它的工作!除了最後一行,我收到了一條錯誤消息,但是當我刪除它時,查詢似乎已經工作 – Aaron

+0

只需要將組放在引號中(固定)(我錯過了那個) – xQbert

+0

我仍然收到錯誤消息:can格式化消息13:896 - 未找到消息文件C:\ Windows \ firebird.msg。 動態SQL錯誤。 SQL錯誤代碼= -104。 令牌未知 - 第41行,第22列。 「組」。 – Aaron