在SQL Query问题中将行连接到列

时间:2015-01-30 15:46:18

标签: sql sql-server concatenation rows for-xml-path

我遇到以下查询结果的问题。我想连接每个客户的product_number,它自己的列只显示每个客户的一行。客户列是varchar。我尝试使用STUFF和FOR XML Path,但我没有得到我想要的结果。

它在“产品”列中为我提供了触及范围内的每个product_number,因此我不会获得每个公司的产品,而是获取整个列表或每个产品行。

SELECT customer_number
  ,first_name_initial
  ,last_name
  ,billing_address_line_1
  ,billing_city
  ,zip_code
  ,phone_number1
  ,email1
  ,STUFF((SELECT ', ' + product_number
  FROM #TempS
  FOR XML PATH ('')), 1, 1, '') [PRODUCTS]
FROM #TempS
GROUP BY customer_number
  ,first_name_initial
  ,last_name
  ,billing_address_line_1
  ,billing_city
  ,zip_code
  ,phone_number1
  ,email1
ORDER BY customer_number

我希望每行阅读下面的每一家公司(我为了便于阅读而缩短了)。

提前致谢。

ROWID customer company  address city  zip_code phone_number email1   PRODUCTS
1     1255400  Company1 CAdd1   City1 10001    111-111-1111 e@c.com  01002, 09999, 09002 091111, 00005     

a busy cat"

这就是诀窍。

SELECT customer_number,
       first_name_initial,
       last_name,
       billing_address_line_1,
       billing_city,
       zip_code,
       phone_number1,
       email1,
       Stuff((SELECT ',' + CONVERT(VARCHAR(5), product_number)
              FROM   #tempsales t2
              WHERE  t1.customer_number = t2.customer_number
                     AND t2.product_number > ''
              FOR xml path('')), 1, 1, '') [Products]
FROM   #tempsales t1
GROUP  BY customer_number,
      first_name_initial,
      last_name,
      billing_address_line_1,
      billing_city,
      zip_code,
      phone_number1,
      email1,
ORDER  BY customer_number

感谢。

2 个答案:

答案 0 :(得分:1)

试试这个:

DECLARE @t TABLE
    (
      ID INT ,
      cust INT ,
      prod NVARCHAR(4)
    )

INSERT  INTO @t
VALUES  ( 1, 1, '0001' ),
        ( 2, 1, '0002' ),
        ( 3, 1, '0003' ),
        ( 4, 1, '0004' ),
        ( 5, 2, '0001' ),
        ( 6, 2, '0002' ),
        ( 7, 2, '0003' ),
        ( 8, 3, '0001' ),
        ( 9, 3, '0002' ),
        ( 10, 3, '0003' )


SELECT  t1.cust ,
        STUFF((SELECT   ', ' + prod
               FROM     @t t2
               WHERE    t2.cust = t1.cust
        FOR   XML PATH('') ,
                  TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM    @t t1
GROUP BY t1.cust

输出:

cust    prod
1       0001, 0002, 0003, 0004
2       0001, 0002, 0003
3       0001, 0002, 0003

答案 1 :(得分:0)

我必须更改FOR XML标准才能使其正常工作。上面的完整查询。

Stuff((SELECT ',' + CONVERT(VARCHAR(5), product_number)
          FROM   #tempsales t2
          WHERE  t1.customer_number = t2.customer_number
                 AND t2.product_number > ''
          FOR xml path('')), 1, 1, '') [Products]