我有一个像这样的表是mysql。我需要得到不包含特定属性的不同doc_id的计数。例如,如果属性为“product”,则结果应为1(即,仅第4个doc_id不包含产品)
+--------+-----------+--------+
| doc_id | attribute | value |
+--------+-----------+--------+
| 1 | product | mobile |
| 1 | model | lumia |
| 1 | camera | 5mp |
| 2 | product | mobile |
| 2 | model | lumia |
| 2 | ram | 1gb |
| 3 | product | mobile |
| 3 | year | 2014 |
| 3 | made-in | china |
| 4 | brand | apple |
| 4 | model | iphone |
| 4 | camera | 5mp |
| 5 | product | camera |
| 5 | brand | canon |
| 5 | price | 20000 |
答案 0 :(得分:2)
您可以使用count(distinct)
select count(distinct doc_id) - count(distinct case when attribute = 'product' then doc_id end)
from table t;
使用子查询,您首先会按doc_id
聚合,然后执行计数:
select count(*)
from (select doc_id, max(attribute = 'product') as has_product
from table t
group by doc_id
) t
where has_product = 0;