试图在这里做一些事情来创建一种摘要数据.我不确定它是最优雅的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
Run Code Online (Sandbox Code Playgroud)
我想查询数据,以便我得到一些代表"直接"销售的东西,这是一个网络和商店销售的总和,因此忽略了挨家挨户和忏悔.
Product Channel Sold
------------------- ----------------------
PC Direct 49
Laptop Direct 3
Speakers Direct 75
DVDs Direct 38
Run Code Online (Sandbox Code Playgroud)
有谁知道我怎么做这个?我正在考虑分组(选择......分组),但我正在尝试的一切都是绝望的失败!大声笑.
提前致谢.
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
Run Code Online (Sandbox Code Playgroud)
再次感谢!
DS
您只需要过滤掉记录channel并使用SUM()on column 聚合它们,Sold特别是每个组product.
SELECT Product,
'Direct' Channel,
SUM(Sold) TOtalSold
FROM TableName
WHERE Channel IN ('Web','Shop')
GROUP BY Product
Run Code Online (Sandbox Code Playgroud)
UPDATE
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
Run Code Online (Sandbox Code Playgroud)
OUTPUT
????????????????????????????????????
? 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 ?
????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)