Skip to content
Advertisement

GROUP BY with Key:Value filters for each group

Given a table with following schema:

RecordId ProcessId Data
80830F00-379C-11EA-96B7-372060281AFC 1 4.2
80830F00-379C-11EA-96B7-372060281AFC 2 445588662211448
80830F00-379C-11EA-96B7-372060281AFC 7 1
791F6D30-379C-11EA-96B7-372060281AFC 1 3.3
791F6D30-379C-11EA-96B7-372060281AFC 2 999999999999999
791F6D30-379C-11EA-96B7-372060281AFC 7 2

So the RecordId represents some grouping key and each ProcessId has its Data.

Now I have a filter which looks like this:

filter: [
    { "1": "3.3" },
    { "2": "999999999999999" }
]

So the key is ProcessId and value is Data.

Question

How can I get all RecordIds which satisfies query meaning that each group (grouped by RecordId) should contain specific processes with specific data.

I believe it should be used like this:

SELECT RecordId
FROM [SomeTable]
GROUP BY RecordId
HAVING --- the row with ProcessId = 1 AND Data = '3.3'
    AND --- the row with ProcessId = 2 AND Data = '999999999999999'

Advertisement

Answer

You can use having with case:

SELECT RecordId
FROM [SomeTable]
GROUP BY RecordId
HAVING SUM(CASE WHEN ProcessId = 1 AND Data = '3.3' THEN 1 ELSE 0 END) > 0 AND
       SUM(CASE WHEN ProcessId = 2 AND Data = '999999999999999' THEN 1 ELSE 0 END) > 0;
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement