基于另一列的聚合结果选择两列之一。

huangapple go评论120阅读模式
英文:

Choose between two columns based on aggregate of another column

问题

如果PEOPLE与其他行相同但COMPANY不同,则给我SERVICE_1;如果PEOPLE与其他行相同且COMPANY也相同,则给我SERVICE2。我该如何在T-SQL中编写这段代码?可以使用row_number子句来实现吗?

原始数据:

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

期望结果:

PEOPLE COMPANY SERVICE
KRISH AA HYDRO
KRISH BB NULL
JOHN CC ROAD
JOHN CC ELECY
JOHN CC GAS
英文:

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:

PEOPLE COMPANY SERVICE
KRISH AA HYDRO
KRISH BB NULL
JOHN CC ROAD
JOHN CC ELECY
JOHN CC GAS

答案1

得分: 2

以下是翻译好的部分:

也许有数种方法可以实现这个目标。其中一种方法是首先分别计算不同的公司数量,然后使用 CASE 表达式将其连接在一起,通过此方式公开服务(示例):

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;
英文:

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;

huangapple
  • 本文由 发表于 2023年7月23日 22:34:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76748792.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定