Sql - 过滤特定类别

Sql - Filtering on certain category

我正在尝试编写 sql,它会给我出现在类别 'blue' 和 'red' 中但不在任何其他类别中的独特设备的数量。

下面是我的简单示例。这个问题的答案是 3 台设备(设备 1、2、5)。

如果有人能给我提示,我将不胜感激。谢谢你。

 device | category 
--------+----------
      1 | blue
      2 | red
      3 | black
      4 | yellow
      4 | blue
      5 | red
      5 | blue

一种方法是将您的 table 加入到识别匹配设备的聚合查询中。

WITH cte AS (
    SELECT Device
    FROM yourTable
    GROUP BY Device
    HAVING SUM(CASE WHEN category NOT IN ('blue', 'red') THEN 1 ELSE 0 END) = 0
)

SELECT t1.Device, t1.Category
FROM yourTable t1
INNER JOIN cte t2
    ON t1.Device = t2.Device;

我们也可以用SUM作为解析函数:

SELECT Device, category
FROM
(
    SELECT Device, category,
        SUM(CASE WHEN category NOT IN ('blue', 'red') THEN 1 ELSE 0 END) OVER
            (PARTITION BY Device) color_sum
    FROM yourTable
) t
WHERE color_sum = 0;

Demo

使用bool_and():

with my_table(device, category) as (
values 
    (1, 'blue'),
    (2, 'red'),
    (3, 'black'),
    (4, 'yellow'),
    (4, 'blue'),
    (5, 'red'),
    (5, 'blue')
)

select device, bool_and(category in ('red', 'blue'))
from my_table
group by device
order by device;

 device | bool_and 
--------+----------
      1 | t
      2 | t
      3 | f
      4 | f
      5 | t
(5 rows)

您的查询可能如下所示:

select device
from my_table
group by device
having bool_and(category in ('red', 'blue'))
order by device;
select distinct device from Test
where category in ('blue','red')
except
select distinct device from Test
where category in (select distinct category from test
                     where category not in ('blue','red'))

或者如果您需要计数:

select count(*)
from
(select distinct device from Test
where category in ('blue','red')
except
select distinct device from Test
where category in (select distinct category from test
                     where category not in ('blue','red'))) a