SQL Server Choose between two columns based on aggregate of another column

yzckvree  于 2023-08-02  发布在  其他
关注(0)|答案(1)|浏览(106)

If PEOPLE are the same as in other rows but COMPANY is different, then give me SERVICE_1 ; if PEOPLE are the same like other rows and COMPANY are also the same then give me SERVICE2 . How can I write code for this in T-SQL? Can it be achieved using the row_number clause?

Original data:
| PEOPLE | COMPANY | SERVICE_1 | SERVICE_2 |
| ------------ | ------------ | ------------ | ------------ |
| KRISH | AA | HYDRO | WATER |
| KRISH | BB | NULL | WATER |
| JOHN | CC | NULL | ROAD |
| JOHN | CC | NULL | ELECY |
| JOHN | CC | NULL | GAS |

Desired results:

PEOPLECOMPANYSERVICE
KRISHAAHYDRO
KRISHBBNULL
JOHNCCROAD
JOHNCCELECY
JOHNCCGAS
pbpqsu0x

pbpqsu0x1#

Probably a dozen ways to do this. One is you can count the distinct companies separately and then join, exposing the service with a CASE expression ( example ):

WITH cte AS 
(
  SELECT PEOPLE, c = COUNT(DISTINCT COMPANY)
  FROM dbo.Something GROUP BY PEOPLE
)
SELECT cte.PEOPLE, s.COMPANY,
  SERVICE = CASE WHEN cte.c = 1 THEN s.SERVICE_2 ELSE s.SERVICE_1 END
FROM cte JOIN dbo.Something AS s
ON cte.PEOPLE = s.PEOPLE;

相关问题