Ms-Access

MS Access SQL 多行合併為一行,包含新列

  • March 21, 2021

我有一個表格,其中包含來自 20 項測試的各個測試項(響應)。有一個 Person_ID、一個 Item_Number 和一個 Item_Response。例子:

Person_ID| Item_Number| Item_Response
1        | 1          | 6
1        | 2          | 9
1        | 3          | 3
1        | 4          | 2
2        | 1          | 5
2        | 2          | 5
2        | 3          | 1
2        | 4          | 8
3        | 1          | 1
3        | 2          | 3
3        | 3          | 5
3        | 4          | 2

需要使用 SQL 查詢轉換為:

Person_ID| Resp1| Resp2| Resp3| Resp4
1        | 6    | 9    | 3    | 2
2        | 5    | 5    | 1    | 8
3        | 1    | 3    | 5    | 2

我正在使用 MS Access SQL

謝謝!

我最近做了類似的事情來“扁平化”一些數據。

我發現使用 CASE 表達式最容易:

   SELECT Person_ID,
   SUM(CASE WHEN Item_Number=1 THEN Item_Response ELSE 0 END) AS Resp1,
   SUM(CASE WHEN Item_Number=2 THEN Item_Response ELSE 0 END) AS Resp2,
   SUM(CASE WHEN Item_Number=3 THEN Item_Response ELSE 0 END) AS Resp3,
   SUM(CASE WHEN Item_Number=4 THEN Item_Response ELSE 0 END) AS Resp4

   FROM tablename

   GROUP BY Person_ID;

那是標準的SQL。在 MS Access 中,您可能需要將 CASE 替換為 IIF():

   SELECT Person_ID,
   SUM(IIF(Item_Number=1, Item_Response, 0)) AS Resp1,
   SUM(IIF(Item_Number=2, Item_Response, 0)) AS Resp2,
   SUM(IIF(Item_Number=3, Item_Response, 0)) AS Resp3,
   SUM(IIF(Item_Number=4, Item_Response, 0)) AS Resp4

   FROM tablename

   GROUP BY Person_ID;

假設您的表是 MyTable,您只需使用以下語句創建查詢:

TRANSFORM First(MyTable.Item_Response) AS FirstOfItem_Response
SELECT MyTable.Person_ID
FROM MyTable
GROUP BY MyTable.Person_ID
PIVOT "Resp" & MyTable.Item_Number;

引用自:https://dba.stackexchange.com/questions/147332