-1

有没有更好更简单的方法来做到这一点?假设我有 500 多个组。这需要很多连接才能完成。在下面的示例中,我只有 3 个 LEFT OUTER 联接,因此相对容易。如果有更好的建模方法,没有这些奇怪的连接,那也可能很好看(也许有一个映射表/桥接表)?

SELECT
     [user].id,
     '2010-01-01' AS begin_date,
     group_a.source AS group_a_id,
     group_b.source AS group_b_id,
     group_c.source AS group_c_id
FROM
    (select distinct id FROM [user]) [user]
    LEFT OUTER JOIN [group] group_a ON user.id = group_a.user_id and group_a.type in ('1', '2', '5')
    LEFT OUTER JOIN [group] group_b ON user.id = group_b.user_id and group_b.type = '3'
    LEFT OUTER JOIN [group] group_c ON user.id = group_c.user_id and group_c.type = '4'
4

2 回答 2

1

你在找这个吗?

SELECT
     [user].id,
     '2010-01-01' AS begin_date,
     CASE WHEN group_a.type = '1'
               OR group_a.type = '2'
               OR group_a.type = '5' THEN group_a.source END AS group_a_id,
     CASE WHEN group_a.type = '3' THEN group_a.source END AS group_b_id,
     CASE WHEN group_a.type = '4' THEN group_a.source END AS group_c_id
FROM
    (select distinct id FROM [user]) [user]
    LEFT OUTER JOIN [group] group_a ON user.id = group_a.user_id
于 2013-10-10T22:49:59.523 回答
0

尝试

SELECT
     [user].id,
     '2010-01-01' AS begin_date,
     CASE WHEN group_a.type = '1'
               OR group_a.type = '2'
               OR group_a.type = '5' THEN group_a.source END AS group_a_id,
     CASE WHEN group_a.type = '3' THEN group_a.source END AS group_b_id,
     CASE WHEN group_a.type = '4' THEN group_a.source END AS group_c_id
FROM
    (select distinct id FROM [user]) [user]
    LEFT OUTER JOIN [group] group_a ON user.id = group_a.user_id
于 2013-10-10T22:52:21.043 回答