SQL查询创建跨列
我有这张桌子SQL查询创建跨列,sql,sql-server,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 | quanti
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
提前谢谢
Niko如果您只关心两种产品,那么这就是简单的聚合:
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;
如果您关心两个以上的产品,则需要进行聚合字符串连接。这在SQLServer中有点痛苦。首先通过谷歌搜索“sql server聚合字符串连接”。这是s的示例:
----- 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
客户产品数量
CLI01 A+B 30
CLI02只有一个31
CLI03 A+C 22
你试过使用这些东西吗?这会给你你所需要的。从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
是否每两个以上的产品?应该是“谢谢你们”的动态复制品。史蒂夫,你怀疑它是完美的。我已经在交叉应用中添加了2个不同的。对不起,Steve,但是如果我想设置“+”?
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