SQL Server - count records by combination

0

I need to query the sql server so that it identifies to me when the 1,2 and 3 or 2 and 3 combinations of the "desc" column are present for repeated values of the "cod" column, the result should be returned as 1 for found and 0 not found. Does anyone know how this query can be done? Thank you.

    
asked by anonymous 25.04.2018 / 18:47

1 answer

1

You can use a query to parse combinations using STUFF , see this link: link

And from this query, parse the combined values to return the ID with CASE . The query looks like this:

WITH combinado (cod, descr) 
     AS (SELECT cod, 
                -- combina os valores 1,2 e 3, agrupado por cod
                Stuff((SELECT ', ' + Cast(descr AS CHAR(1)) 
                       FROM   teste AS t2 
                       WHERE  t2.cod = t.cod 
                       ORDER  BY descr 
                       FOR xml path(N'')), 1, 2, N'') AS descr 
         FROM   teste t) 
SELECT cod, 
       descr, 
       CASE descr 
         WHEN '1, 2, 3' THEN 1 
         WHEN '2, 3' THEN 1 
         ELSE 0 
       END AS ID 
FROM   combinado 

See an example working here on this fiddle : link

    
25.04.2018 / 19:17