代码之家  ›  专栏  ›  技术社区  ›  Mahks

如何返回sum()的行

  •  0
  • Mahks  · 技术社区  · 15 年前

    我现在发现我原来的表结构不好,所以想改变它。 但是我很难设计查询来获得新结构行中的总计。

    current structure:
    +----------+-------+-------+-------+-------+
    |   state  | shop  | item0 | item1 | item2 | 
    +----------+-------+-------+-------+-------+
    |    5     |  0    |   1   |   2   |   3   |
    |    5     |  1    |   1   |   2   |   3   |
    |    5     |  2    |   1   |   2   |   3   |
    |    4     |  3    |   1   |   2   |   3   |
    +----------+-------+-------+-------+-------+
    (quantities of items at shop)
    

    我想换这两张桌子:

    shops table
    +---------+--------+
    | shop_id | state  |
    +---------+--------+
    |    0    |    5   |
    |    1    |    5   |
    |    2    |    5   |
    |    3    |    4   |
    +---------+--------+
    
    items table
    +------------+--------------+
    |   shop  | item | quantity | 
    +------------+--------------+
    |    0    |  0   |    1     |
    |    0    |  1   |    2     |
    |    0    |  2   |    3     |
    |    1    |  0   |    1     |
    |    1    |  1   |    2     |
    |    1    |  2   |    3     |
    |    2    |  0   |    1     |
    |    2    |  1   |    2     |
    |    2    |  2   |    3     |
    |    3    |  0   |    1     |
    |    3    |  1   |    2     |
    |    3    |  2   |    3     |
    +------------+--------------+
    

    旧布局允许按行获取总计的简单查询:

    SELECT state,SUM(item0) t0,SUM(item1) t1,SUM(item2) t2
    FROM shops
    WHERE state=5 
    
        +--------+---------+---------+----------+
        | state  |    t0   |    t1   |    t2    |
        +--------+---------+---------+----------+
        |    5   |    3    |     6   |    9     |
        +--------+---------+---------+----------+
    
    With the new structure,
    I can get the totals in column as follows:
    
    SELECT item,SUM(quantity) total
    FROM shops
    LEFT JOIN items ON shop=shopid
    WHERE state=5
    GROUP by item
    +--------+---------+
    |  item  |  total  |
    +--------+---------+
    |    0   |    3    |
    +--------+---------+
    |    1   |    6    |
    +--------+---------+
    |    2   |    9    |
    +--------+---------+
    
    but how do I get the totals in rows:
    +--------+---------+---------+----------+
    | state  |    t0   |    t1   |     t2   |
    +--------+---------+---------+----------+
    |    4   |     1   |     2   |      3   |
    |    5   |     3   |     6   |      9   |
    +--------+---------+---------+----------+
    
    1 回复  |  直到 15 年前
        1
  •  1
  •   Bjoern    15 年前

    你可以再试试 JOIN S:

    SELECT S.state, 
        SUM(T0.quantity) AS "T0",
        SUM(T1.quantity) AS "T1",
        SUM(T2.quantity) AS "T2"
    FROM shops AS S
    LEFT JOIN items AS T0 ON S.shop_id = T0.shop_id AND T0.item=0
    LEFT JOIN items AS T1 ON S.shop_id = T1.shop_id AND T1.item=1
    LEFT JOIN items AS T2 ON S.shop_id = T2.shop_id AND T2.item=2
    GROUP BY S.state
    

    也许有更简单的方法。