尝试在此处执行某些操作以创建一种摘要数据。我不确定它是最优雅的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
我想查询数据,所以我得到的东西代表“直接”销售,这是一个Web和商店销售的总和,因此忽略了挨家挨户和忏悔。
Product Channel Sold
------------------- ----------------------
PC Direct 49
Laptop Direct 3
Speakers Direct 75
DVDs Direct 38
有谁知道我怎么做这个? 我正在考虑分组(选择......分组),但我正在尝试的一切都是绝望的失败!洛尔。
提前致谢。
DS
EDIT!
如果我想把挨家挨户和忏悔放在一起作为“次要”怎么办?这很容易实现吗?所以我在寻找......
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
答案 0 :(得分:6)
您只需按channel
过滤掉记录,然后使用SUM()
列Sold
为每个组product
汇总这些记录。
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 ║
╚══════════╩═══════════╩═══════════╝