Ms-Access

訪問:如何在查詢中合併兩行數據

  • July 16, 2016

我有一個格式如下的基本數據集。

Sex1    | Sex2    | Number|  
F       |         | 5     |   
M       |         | 8     |
M       | F       | 5     |   
F       | F       | 3     |
M       | F       | 2     |   
F       | M       | 1     |
F       | F       | 9     |   
M       | M       | 3     |

我想使用 SQL 創建一個查詢,該查詢按性別組合從價格中生成總計,如下所示:

Sex | Total Number
F   |    5
M   |    8
MF  |    8 
FF  |    12
MM  |    3

但是,我正在努力尋找一種將 FM 和 MF 類別拉到同一行的方法。我擁有的使它們與眾不同的程式碼的形式是

SELECT Sex1 & "" & Sex2 AS Sex, Sum(Number) AS [Total Number]
FROM TableName
GROUP BY Sex1 & "" & Sex2

有沒有一種簡單的方法來組合行?

您可以使用CASE表達式或IIf()函式首先對兩個值進行排序,然後按它們進行分組:

CASE表達式:

SELECT CASE WHEN Sex1 < Sex2 THEN Sex1 ELSE Sex2 END 
      & CASE WHEN Sex1 < Sex2 THEN Sex2 ELSE Sex1 END AS Sex,
      Sum(Number) AS [Total Number]
FROM TableName
GROUP BY CASE WHEN Sex1 < Sex2 THEN Sex1 ELSE Sex2 END,
        CASE WHEN Sex1 < Sex2 THEN Sex2 ELSE Sex1 END ;

IIf()功能:

SELECT IIf(Sex1 < Sex2, Sex1, Sex2) & IIf(Sex1 < Sex2, Sex2, Sex1) AS Sex,
      Sum(Number) AS [Total Number]
FROM TableName
GROUP BY IIf(Sex1 < Sex2, Sex1, Sex2),
        IIf(Sex1 < Sex2, Sex2, Sex1) ;

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