简化mySQL

时间:2018-03-22 07:17:06

标签: mysql

我有一个按类别分组的返回集。

Category    Total Transactions
============================== 
A                1070 
B                 106
C                  30

我想用额外条件过滤它,这是每个类别的一些项目(假设我们使用item_codes)需要从总交易中排除,例如: A类应排除两个项目:1,3 B类应排除三个项目:2,3,5 C类应排除两个项目:4,5

Category    Total Transactions
==============================
A             570 (after removed all transactions which contains items 1 & 3)
B              76 (after removed all transactions which contains items 2, 3 & 5)
C              10 (after removed all transactions which contains items 4 & 5)

我尽量避免使用像:

这样的子查询
SELECT Category, count(id) as 'Total Transactions' FROM TABLE WHERE Category='A' AND items NOT IN (1,3);
SELECT Category, count(id) as 'Total Transactions' FROM TABLE WHERE Category='B' AND items NOT IN (2,3, 5);
SELECT Category, count(id) as 'Total Transactions' FROM TABLE WHERE Category='C' AND items NOT IN (4, 5);

还有其他想法吗?

sum(case when Category = 'A' then total_transactions else 0 end) as 'A',
sum(case when Category = 'B' then total_transactions else 0 end) as 'B'

...但我无法将“NOT IN(4,5)”中的项目合并到where子句中。

感谢。

1 个答案:

答案 0 :(得分:0)

SELECT Category, count(id) as 'Total Transactions' 
FROM TABLE 
WHERE (Category='A' AND items NOT IN (1,3)) OR
      (Category='B' AND items NOT IN (2,3, 5)) OR
      (Category='C' AND items NOT IN (4, 5))
GROUP BY Category;