SQL Pivot MIN (COUNT (

I have a complex MS SQL 2005 query with PIVOT in it ...

I have the following data:

Data ( clients left join visits ):
ClientID VisitID ServiceID
1        34      5
1        36      2
1        36      5
1        45      2
1        48      2
1        60      2
2        44      1
3        48      2
3        78      3
3        79      2

And I need this:

ID [1] [2] [3] [4] [5]
1   0  1   0   0   1
2   1  0   0   0   0
3   0  1   1   0   0

I am using a SQL query:

select * from 
         (select clients.ClientID, clients.serviceID FROM clients left join visits on visit.cliendid=clients.clientid ) e 
         pivot ( COUNT(serviceID) for serviceID in ([1],[2],...,[54]) ) p

But this SQL query does not do what I want, instead it does this:

ID [1] [2] [3] [4] [5]
1   0  4   0   0   2
2   1  0   0   0   0
3   0  2   1   0   0

I need all the data in the columns to be either 0 or 1, as in, 0 should never use this service, 1 should use this service ... How to do this?

It would be great if I could do pivot (Math.MIN (COUNT (serviceID), 0) for ... or if I could do (CASE (COUNT (serviceID)> 0) THEN 1 ELSE 0 for .., but it will not allow me.

+3
source share
1 answer
SELECT  *
FROM    (
        SELECT  DISTINCT clients.ClientID, clients.serviceID
        FROM    clients
        ) e 
PIVOT   (
        COUNT(serviceID)
        FOR serviceID in ([1],[2])
        ) p
+2
source

Source: https://habr.com/ru/post/1718495/


All Articles