5

试图在这里做一些事情来创建一种汇总数据。我不确定它是否会是最优雅的 sql 代码!

我有下表

Product             Channel         Sold
-------------------     ----------------------  
PC                  Web             48
Laptop              Web             2
Speakers            Web             74
DVDs                Web             33
PC                  Shop            1
Laptop              Shop            1
Speakers            Shop            1
DVDs                Shop            5
PC                  Door-to-door    7
Laptop              Door-to-door    16
Speakers            Door-to-door    9
DVDs                Door-to-door    21
PC                  Referals        7
Laptop              Referals        16
Speakers            Referals        9
DVDs                Referals        21

我想查询数据,所以我得到一些代表“直接”销售的东西,它是网络和商店销售的总和,因此忽略了门到门和推荐。

Product             Channel         Sold
-------------------     ----------------------  
PC              Direct          49
Laptop          Direct          3
Speakers        Direct          75
DVDs            Direct          38

有谁知道我该怎么做?我在考虑 Group by(选择 .... group by),但我正在尝试的一切都是绝望的失败!哈哈。

提前致谢。

DS

编辑!

如果我想把门到门和推荐一起作为“次要”怎么办?这很容易实现吗?所以我在寻找...

Product             Channel         Sold
-------------------     ----------------------  
PC              Direct          49
Laptop          Direct          3
Speakers        Direct          75
DVDs            Direct          38
PC              Secondary       14
Laptop          Secondary       32
Speakers        Secondary       18
DVDs            Secondary       42

再次感谢!

DS

4

1 回答 1

6

您只需要过滤出记录并使用每个组的列channel聚合它们,特别是.SUM()Soldproduct

SELECT  Product,    
        'Direct' Channel,
        SUM(Sold) TOtalSold
FROM    TableName
WHERE   Channel IN ('Web','Shop')
GROUP   BY Product

更新

SELECT  Product,    
        CASE    WHEN Channel IN ('Web','Shop') 
                THEN 'Direct'
                ELSE 'Secondary'
        END Channel,
        SUM(Sold) TOtalSold
FROM    TableName
GROUP   BY Product,
        CASE    WHEN Channel IN ('Web','Shop') 
                THEN 'Direct'
                ELSE 'Secondary'
        END 
ORDER   BY Channel

输出

╔══════════╦═══════════╦═══════════╗
║ PRODUCT  ║  CHANNEL  ║ TOTALSOLD ║
╠══════════╬═══════════╬═══════════╣
║ Laptop   ║ Direct    ║         3 ║
║ Speakers ║ Direct    ║        75 ║
║ DVDs     ║ Direct    ║        38 ║
║ PC       ║ Direct    ║        49 ║
║ Laptop   ║ Secondary ║        32 ║
║ Speakers ║ Secondary ║        18 ║
║ DVDs     ║ Secondary ║        42 ║
║ PC       ║ Secondary ║        14 ║
╚══════════╩═══════════╩═══════════╝
于 2013-06-03T14:17:00.133 回答