2016-07-07 130 views
0

我試圖在兩個字段上組合,並返回第三個字段,該字段是前兩個字段的共同值,產品ID。這裏是我的數據:T-SQL如何GROUP BY兩個字段並連接另一個

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和價格列,但不能連接它們共有的領土:

SELECT Currency, Price 
FROM TerritoryPricing 
WHERE ProductID = 1 
GROUP BY Currency, Price 

如何連接區域?

+0

Google:「SQL Server聚合字符串連接」 –

+0

看這篇文章http://stackoverflow.com/questions/3368942/grouped-string-aggregation-listagg-for-sql-server – are

+0

http://sqlperformance.com/2014/08/t-sql-queries/sql-server-groupped-concatenation –

回答

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 
+0

這很好,謝謝。我唯一需要添加的是子查詢WHERE子句中的「WHERE ProductID = 1」。謝謝! –

0

可以使用的毗連:

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 
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 
相關問題