SQL查询创建交叉列

时间:2017-02-21 15:19:38

标签: sql sql-server

我有这张桌子

customer |  product | quantity
-------------------------------
CLI01    | A        | 10
CLI01    | B        | 20
CLI02    | A        | 31
CLI03    | A        | 10
CLI03    | C        | 12

我想在SQL Server中创建这个输出:

customer | crossProduct | quantity
-----------------------------------
CLI01    | A+B          | 30
CLI02    | Only A       | 31
CLI03    | B+C          | 22

提前致谢

尼科

3 个答案:

答案 0 :(得分:1)

如果您只关心两种产品,那么这是简单的聚合:

select customer,
       (case when count(distinct product) > 2 then 'Lots of Products'
             when min(product) = max(product) then 'Only ' + min(product)
             else min(product) + '+' + max(product)
        end) as crossproduct,
       sum(quantity)
from t
group by customer;

如果您关心两种以上的产品,那么您需要进行聚合字符串连接。这在SQL Server中有点痛苦。从谷歌搜索" sql server聚合字符串连接"。

答案 1 :(得分:0)

这是样本:

----- Test Data ----------
DECLARE @TestData TABLE (customer VARCHAR(10),product VARCHAR(10),quantity INT)
INSERT INTO @TestData
SELECT 'CLI01','A',10 UNION ALL
SELECT 'CLI01','B',20 UNION ALL
SELECT 'CLI02','A',31 UNION ALL
SELECT 'CLI03','A',10 UNION ALL
SELECT 'CLI03 ','C',12
-----  Query -------------
SELECT customer,CASE WHEN COUNT( DISTINCT t.product)=1 THEN 'Only ' ELSE '' END + LEFT(c.product,LEN(c.product)-1) AS Product,SUM(quantity) AS quantity 
FROM @TestData AS t
CROSS APPLY(SELECT a.product+'+' FROM @TestData AS a WHERE a.customer=t.customer FOR XML PATH('')) c(product)
GROUP BY customer,c.product
ORDER BY t.customer
customer    Product quantity
CLI01   A+B 30
CLI02   Only A  31
CLI03   A+C 22

答案 2 :(得分:0)

你尝试过用过的东西吗?这将为您提供所需。从sql 2008开始,可以根据需要使用尽可能多的产品。

CREATE TABLE x (customer VARCHAR (20), product CHAR(1), quantity INT )
INSERT INTO x
  VALUES( 'CLI01', 'A', 10),
        ( 'CLI01', 'B', 20),
        ( 'CLI02', 'A', 31),
        ( 'CLI03', 'A', 10),
        ( 'CLI03', 'C', 12)

SELECT  x1.customer, x3.Products, SUM(x1.quantity)
FROM    x x1
        CROSS APPLY ( SELECT  Products = STUFF( (select '+' + product AS [text()]
                      FROM    x  x2
                      WHERE   x2.customer = x1.customer
                      FOR XML PATH ('') ), 1, 1,'') ) x3
GROUP BY x1.customer, x3.Products