简体   繁体   English

从输出中排除一些记录的 SQL 查询

[英]SQL query to exclude some records from the output

I have a query:我有一个疑问:

SELECT 
       c.device_item_id
     , DATEDIFF(day, (DATE(c.tstmp)), sysdate) AS day
     , (DATE(c.tstmp)) AS date
     , COUNT(c.val) AS count
FROM (
  SELECT 
      b.device_item_id
    , TO_TIMESTAMPTZ(a.tstamp) AT TIME ZONE 'UTC' AS tstmp
    , MAX(a.im_utilization) AS val
    FROM physical_memstats_rate AS a
    INNER JOIN v_poll_item AS b ON a.item_id = b.item_id
    WHERE b.device_item_id IN (
        SELECT item_id
        FROM v_poll_item
        WHERE device_item_id IN (
            SELECT member_item_id
            FROM etl_group_membership
            WHERE group_item_id = 335640
            )
        )
    AND a.tstamp > 1624233600 AND a.tstamp <= 1623801599
    GROUP BY 1, 2 ORDER BY 1, 2 DESC
    ) AS c
WHERE c.val > 48
GROUP BY 1, 2, 3
HAVING COUNT(c.val) > 12
ORDER BY 3, 1 DESC;

The result of this query is:这个查询的结果是:

device_item_id | day | date       | count
==========================================
332191         | 7   | 2021-06-17 | 287
298711         | 7   | 2021-06-17 | 104
117722         | 7   | 2021-06-17 | 287
104151         | 7   | 2021-06-17 | 287
5316           | 7   | 2021-06-17 | 287
332191         | 6   | 2021-06-18 | 288
117722         | 6   | 2021-06-18 | 288
104151         | 6   | 2021-06-18 | 288
5316           | 6   | 2021-06-18 | 288
332191         | 5   | 2021-06-19 | 288

I want to narrow down this result to exclude the results where the count(device_item_id) < 2 (meaning it will exclude device_item_id = 298711) but still be able to select all other columns in the output.我想缩小此结果的范围以排除 count(device_item_id) < 2(意味着它将排除 device_item_id = 298711)但仍然能够选择输出中的所有其他列的结果。

I tried using EXCEPT but that makes me repeat the entire query again.我尝试使用 EXCEPT 但这让我再次重复整个查询。

Please can someone suggest how to achieve it in simplest possible way?请有人建议如何以最简单的方式实现它?

Thanks谢谢

You can use a subquery or CTE:您可以使用子查询或 CTE:

with t as (
      <your query here>
     )
select t.*
from (select t.*,
             count(*) over (partition by device_item_id) as cnt
      from t
     ) t
where cnt >= 2;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM