如何在SQL中的同一行上加入结果?

时间:2017-01-09 20:54:55

标签: sql sql-server join max resultset

这是我上一个问题的后续问题:How to get multiple rows of data into different columns

我的查询与上一个问题中提供的查询非常相似:

SELECT AccountID,
   Value1 = MAX(CASE WHEN RN = 1 THEN Value END),
   Value2 = MAX(CASE WHEN RN = 2 THEN Value END),
   Value3 = MAX(CASE WHEN RN = 3 THEN Value END)
FROM
(
SELECT AccountID,
       Value = CONVERT(VARCHAR(50), Value), -- Cast GUID as VARCHAR(50) to use MAX() in the outer query.
       RN = ROW_NUMBER() OVER (PARTITION BY AccountID ORDER BY Value)
FROM @myTable
) T
GROUP BY AccountID;

我已经将查询输出到一行,如下所示:

AccountID                              Value1                                 Value2                                 Value3
6D68E2C9-4BF8-433B-8BC3-57D87348D034   F0BFA1B1-744A-4DBC-BE27-19D1618D77EA   E22A4B08-40DC-42E5-BC15-72A6912D0D66   A955B30C-5352-4B48-9E96-8A831AFA0751    

我现在遇到的问题是我需要使用Value1,Value2和Value3(另一个表中的主键)中的值从其他数据表中获取值。如果我要加入这些值,我最终会再次获得三行。我是否必须做类似的事情或使用支点?

我最终会想要这样的内容:

Account Id                              Value1Table.Color    Value2Table.Color    Value3Table.Color   Value1Table.Size    Value2Table.Size 
6D68E2C9-4BF8-433B-8BC3-57D87348D034    Blue                 Red                  Orange              Large             Small

1 个答案:

答案 0 :(得分:0)

在转动之前进行查找

SELECT AccountID,
       Value1 = MAX(CASE WHEN RN = 1 THEN Value END),
       Value2 = MAX(CASE WHEN RN = 2 THEN Value END),
       Value3 = MAX(CASE WHEN RN = 3 THEN Value END)
FROM (SELECT AccountID,
             Value = othertable.color.
             RN = ROW_NUMBER() OVER (PARTITION BY AccountID ORDER BY Value)
      FROM @myTable t JOIN
           othertable ot
           ON ot.value = t.value
     ) T
GROUP BY AccountID;