我试图在2个字段上进行分组并返回第三个字段,该字段是前两个字段的值与另一个字段的值的串联,具有给定的ProductID。这是我的数据:
ProductID Currency Price Territory
1 USD 6.99 US
1 EUR 4.99 GR
1 EUR 4.99 HU
1 EUR 4.99 LT
2 USD 7.99 US
2 EUR 5.99 GR
2 EUR 5.99 HU
我希望结果像这样回来:
ProductID Currency Price Territories
1 USD 6.99 US
1 EUR 6.99 GR, HU, LT
我可以提取Currenty和Price列,但不能连接他们共有的地区:
SELECT Currency, Price
FROM TerritoryPricing
WHERE ProductID = 1
GROUP BY Currency, Price
如何连接地区?
答案 0 :(得分:0)
你可以使用Concat:
SELECT ProductID, Currency, Price, CONCAT(Territory)
GROUP BY territory
FROM employee_tbl;
或创建一个像此一样的colace函数
CREATE FUNCTION [dbo].[terr]
(
@territoryID int
)
RETURNS varchar(max)
AS
BEGIN
declare @output varchar(max)
select @output = COALESCE(@output + ', ', '') + territory
from TerritoryPricing
where territoryid = @territoryID
return @output
END
GO
SELECT UserID, [dbo].terr(territoryID)
FROM TerritoryPricing
GROUP BY territory
GO
答案 1 :(得分:0)
测试此代码
DECLARE @S VARCHAR(8000)
SELECT
Currency,
Price ,
Territories = (Select @S = @S + Territory FROM TerritoryPricing as T2 WHERE T1.Currency = T2.Currency AND T1.Price = T2.Price) ,
Empty = (select @S ='')
FROM TerritoryPricing as T1
WHERE ProductID = 1
GROUP BY Currency, Price
答案 2 :(得分:0)
您可以使用SQL的XML处理来生成带有SQL 2000及更高版本的连接列表:
create table #TerritoryPricing ( ProductID int, Currency varchar(3), Price decimal(10,2), Territory varchar(2))
insert into #TerritoryPricing values (1,'USD',6.99,'US')
insert into #TerritoryPricing values (1,'EUR',4.99,'GR')
insert into #TerritoryPricing values (1,'EUR',4.99,'HU')
insert into #TerritoryPricing values (1,'EUR',4.99,'LT')
insert into #TerritoryPricing values (2,'USD',7.99,'US')
insert into #TerritoryPricing values (2,'EUR',5.99,'GR')
insert into #TerritoryPricing values (2,'EUR',5.99,'HU')
SELECT Currency, Price,
SUBSTRING(
(SELECT ( ',' + ltrim(rtrim(Territory)))
FROM #TerritoryPricing t2
WHERE t1.Currency = t2.Currency
and t1.Price = t2.Price
and ProductID = 1
ORDER BY t2.Territory
FOR XML PATH('')
), 2, 8000) Territories
FROM #TerritoryPricing t1
WHERE ProductID = 1
GROUP BY Currency, Price