LEFT JOIN SUBSTITUTE

时间:2017-09-05 10:53:45

标签: sql sql-server pivot left-join transpose

我有一个表TOPIC(Article_ID,ROOT_TOPIC_ID,LEVEL,TOPIC_NAME)。 选择结果如下:

enter image description here

我需要转置结果集,但我为每个级别使用多个左连接。

我想要的结果集是这样的:

enter image description here

多个左自联接正在弃用性能,并且无法在字符串列上进行旋转(不确定)!!

有什么建议吗?

2 个答案:

答案 0 :(得分:4)

左边连接没有任何内容可以阻止你转动结果。如果性能很差,则可能是作为连接键的列未正确或适当地编入索引。 SQLServer Management Studio是否会建议您删除任何索引?

SELECT
  Article_ID, Root_Topic_ID, [0], [1], [2], [3], [4], [5], [6]
FROM
  (your select query here) src
PIVOT
(
  MAX(Topic_name)
  FOR LEVEL IN ([0], [1], [2], [3], [4], [5], [6])
) pvt

影响原始查询性能的数据透视没有任何意义;实际上,根据定义,原始查询必须在可以旋转之前运行。 Pivot只是GROUP / MAX(CASE WHEN)的另一种格式语法,你在另一个答案中给出了

答案 1 :(得分:3)

使用CASE和条件聚合

SELECT ArticleID, ROOT_TOPIC_ID, 
   MAX (CASE WHEN level = 0 THEN Topic_name END) as Level0,
   MAX (CASE WHEN level = 1 THEN Topic_name END) as Level1,
   MAX (CASE WHEN level = 2 THEN Topic_name END) as Level2,
   MAX (CASE WHEN level = 3 THEN Topic_name END) as Level3,
   MAX (CASE WHEN level = 4 THEN Topic_name END) as Level4,
   MAX (CASE WHEN level = 5 THEN Topic_name END) as Level5,
   MAX (CASE WHEN level = 6 THEN Topic_name END) as Level6
FROM Topic
GROUP BY ArticleID, ROOT_TOPIC_ID

使用子查询也是可能的,但是,在这种情况下,条件聚合的性能可能会更好。

SELECT ArticleID, ROOT_TOPIC_ID, 
   (
       SELECT top 1 Topic_name FROM Topic t WHERE t.ArticleID = Topic.ArticleID AND t.ROOT_TOPIC_ID = Topic.ROOT_TOPIC_ID AND level = 0
   ) as Level0,
   (
       SELECT top 1 Topic_name FROM Topic t WHERE t.ArticleID = Topic.ArticleID AND t.ROOT_TOPIC_ID = Topic.ROOT_TOPIC_ID AND level = 1
   ) as Level1,
   -- an so on
FROM Topic
GROUP BY ArticleID, ROOT_TOPIC_ID