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.
I tried using EXCEPT but that makes me repeat the entire query again.
Please can someone suggest how to achieve it in simplest possible way?
Thanks
You can use a subquery or 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;