如何编写基于列值组合行的自联接?

时间:2014-04-08 18:56:47

标签: mysql sql

我搜索过但无法找到这种情况的答案。我有一个包含2.5密码行帐户的表。这些帐户每个至少出现3次,并由字母数字标识符account_id标识。每个帐户的3行都是可识别的,除了2列,profile_name,它包含3个字符串值中的1个(我们称之为'one,'two'和'three')和distributor_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

2 个答案:

答案 0 :(得分:2)

如果您最多可以拥有三个profile_names,则可以像这样加入您的表:

SELECT
  t1.account_id,
  t1.distributor_id AS distributor_one_id,
  t2.distributor_id AS distributor_two_id,
  t3.distributor_id AS distributor_three_id
FROM
  yourtable t1 LEFT JOIN yourtable t2
  ON t1.account_id = t2.account_id
     AND t2.profile_name = 'two'
  LEFT JOIN yourtable t3
  ON t1.account_id = t3.account_id
     AND t3.profile_name = 'three'
WHERE
  t1.profile_name = 'one'

请参阅小提琴here

答案 1 :(得分:2)

您可以更有效地执行此操作:

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