使用STUFF组合行

时间:2013-08-14 21:47:04

标签: sql

这是我到目前为止所做的,但它显示的结果太多了。它将描述行组合在一起很好,但它正在为每个结果执行此操作。我基本上想要它所以只有3行。每个班级http://prntscr.com/1la4j2

一个
    /* 3. List the part number, part description, and item class for each pair of parts that are in the same item
class */
SELECT 
  t1.partnum,
  STUFF((
    SELECT ', ' + t2.description 
    FROM part t2
    WHERE t1.class = t2.class
    FOR XML PATH (''))
  ,1,2,'') AS description, t1.class
FROM part t1

1 个答案:

答案 0 :(得分:0)

您可以从SELECT

中删除t1.partnum

或者一起列出Partnum和Description:

SELECT DISTINCT
  STUFF((
    SELECT ', ' t2.PartNum + '-' + t2.description 
    FROM part t2
    WHERE t1.class = t2.class
    FOR XML PATH (''))
  ,1,2,'') AS description, t1.class
FROM part t1

或者将partnum放入单独的列表中,例如:

SELECT DISTINCT
  STUFF((
    SELECT ', ' + t3.partnum
    FROM part t3
    WHERE t1.class = t3.class
    FOR XML PATH (''))
  ,1,2,'') AS partnum
  ,STUFF((
    SELECT ', ' + t2.description 
    FROM part t2
    WHERE t1.class = t2.class
    FOR XML PATH (''))
  ,1,2,'') AS description
  , t1.class
FROM part t1