搜尋

首頁  >  問答  >  主體

將標題重寫為:使用反向值對列進行SQL分組

假設我有一個像這樣的表:

+---+---+---+---+---+
|G1 |G2 |G3 |G4 | V |
+---+---+---+---+---+
| A | B | C | D | 2 |
| E | F | G | H | 4 |
| C | D | A | B | 2 |
| E | F | G | H | 3 |
| E | I | G | L | 7 |
+---+---+---+---+---+

其中G1、G3是VARCHAR型,G2、G4是INT型別

如果我在G1..G4上進行簡單的GROUP BY,我會得到:

SELECT G1,G2,G3,G4,SUM(V) as V FROM Table GROUP BY G1, G2, G3, G4;

    +---+---+---+---+---+
    |G1 |G2 |G3 |G4 | V |
    +---+---+---+---+---+
    | A | B | C | D | 2 |
    | E | F | G | H | 7 |
    | C | D | A | B | 2 |
    | E | I | G | L | 7 |
    +---+---+---+---+---+

我想知道是否可能在反轉的值G1、G2 <-> G3、G4上進行聚合。 我想要的結果是這樣的:

+---+---+---+---+---+      +---+---+---+---+---+
|G1 |G2 |G3 |G4 | V |      |G1 |G2 |G3 |G4 | V |
+---+---+---+---+---+      +---+---+---+---+---+
| A | B | C | D | 4 |  或  | C | D | A | B | 4 |
| E | F | G | H | 7 |      | E | F | G | H | 7 |
| E | I | G | L | 7 |      | E | I | G | L | 7 |
+---+---+---+---+---+      +---+---+---+---+---+

我嘗試取得反轉的行,但由於重複,我仍然無法在它們上進行聚合。我的測試查詢是:

SELECT DISTINCT *
FROM Table t1
JOIN Table t2 on t1.G1 = t2.G3 and t1.G2=t2.G4 and t1.G3=t2.G1 and t1.G4=t2.G2

    +---+---+---+---+---+---+---+---+---+---+
    |G1 |G2 |G3 |G4 | V |G1 |G2 |G3 |G4 | V |
    +---+---+---+---+---+---+---+---+---+---+
    | A | B | C | D | 2 | C | D | A | B | 2 |
    | C | D | A | B | 2 | A | B | C | D | 2 |
    +---+---+---+---+---+---+---+---+---+---+

P粉548512637P粉548512637465 天前693

全部回覆(1)我來回復

  • P粉042455250

    P粉0424552502023-09-07 00:07:33

    如果我理解正確,將列的順序反轉,使得 A B C D 對應 C D A B。

    select 
             case when(g1 > g3) then g3 else g1 end G1,
             case when(g1 > g3) then g4 else g2 end G2,
             case when(g1 > g3) then g1 else g3 end G3,
             case when(g1 > g3) then g2 else g4 end G4, sum(V)
    from tbl
    group by case when(g1 > g3) then g3 else g1 end,
             case when(g1 > g3) then g4 else g2 end,
             case when(g1 > g3) then g1 else g3 end,
             case when(g1 > g3) then g2 else g4 end

    db<>fiddle

    #

    回覆
    0
  • 取消回覆