我已经搜索过,但是找不到这种情况的答案。我有一张表,其中包含250万行帐户。这些帐户每个帐户至少出现3次,并由字母数字标识符account_id标识。每个帐户的3行都相同,除了2列profile_name外,profile_name包含3个字符串值中的1个(我们分别称其为“ one”,“ two”和“ three”),以及dispatcher_id,后者是数字标识符。结构看起来像这样(不限于这些字段,但它们是我关心的):
account_id profile_name distributor_id
PX198 'one' 123
PX198 'two' 987
PX198 'three' 573
AZ476 'one' 123
AZ476 'two' 652
我的问题是如何编写自我联接查询以返回如下内容:
account_id distributor_one_id distributor_two_id distributor_three_id
PX198 123 987 573
AZ476 123 652 NULL
最佳答案
您可以通过更有效的方式执行此操作:
SELECT
account_id,
MAX(CASE WHEN profile_name = 'one' THEN distributor_id END) as distributor_one_id,
MAX(CASE WHEN profile_name = 'two' THEN distributor_id END) as distributor_two_id,
MAX(CASE WHEN profile_name = 'three' THEN distributor_id END) as distributor_three_id
FROM tbl
GROUP BY account_id
SQL FIDDLE DEMO
关于mysql - 如何编写基于列值组合行的自我联接?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22945873/