2012-02-09 143 views
1

我與SQL Server 2008工作串聯在一列基於其他列

比方說,我有這三個表:

產品

1, "Honda Civic" 
2, "Fiat Ritmo" 
3, "Ford Fiesta" 

ProductGroup

1, 1, 1 
2, 1, 2 
3, 3, 1 
4, 2, 3 
5, 2, 4 
6, 1, 5 

集團

1 American 
2 Asian 
3 European 
4 Old 
5 Fast 

而且我們說,我想查詢這些表,以便得到如下:

"Fiat Ritmo", "European, Old" 
"Honda Civic", "Asian, Fast" 
"Ford Focus", "American" 

我怎樣才能做到這一點?

我在客戶端使用分頁,所以我不能在那裏分組頁面。

感謝您的幫助,

巴里

+1

Ford Focus ==福特嘉年華? – 2012-02-09 08:58:15

+1

@OlegDok:次要實施細節:) – 2012-02-09 09:38:40

+0

@marc_s +500 dude 8-) – 2012-02-09 09:40:35

回答

2

使用FOR XML PATH功能來獲取字符串這樣的分組:

DECLARE @Product TABLE (Id INT PRIMARY KEY, Name NVARCHAR(100) NOT NULL) 
INSERT @Product 
VALUES(1, 'Honda Civic'), (2, 'Fiat Ritmo'), (3, 'Ford Fiesta') 

DECLARE @ProductGroup TABLE(Product INT, Grp INT, PRIMARY KEY(Product, Grp)) 

INSERT @ProductGroup 
VALUES 
(1, 1), 
(1, 2), 
(3, 1), 
(2, 3), 
(2, 4), 
(1, 5) 

DECLARE @Grp TABLE(Id INT PRIMARY KEY, NAME NVARCHAR(100)) 
INSERT @Grp 
VALUES 
(1, 'American'), 
(2, 'Asian'), 
(3, 'European'), 
(4, 'Old'), 
(5, 'Fast') 

SELECT p.name, 
(
    SELECT Name+',' 
    FROM @ProductGroup pg 
    JOIN @Grp g 
     ON pg.Grp = g.Id 
    WHERE pg.Product = p.Id 
    FOR XML PATH('') 
) Groups 
FROM @Product p 
3

事情是這樣的:

首先是一些測試數據:

DECLARE @Product TABLE(ID INT, Name VARCHAR(100)) 
INSERT INTO @Product 
SELECT 1,'Honda Civic' UNION ALL 
SELECT 2,'Fiat Ritmo' UNION ALL 
SELECT 3,'Ford Fiesta' 

DECLARE @ProductGroup TABLE(ID INT,ProductID INT, GroupID INT) 
INSERT INTO @ProductGroup 
SELECT 1, 1, 1 UNION ALL 
SELECT 2, 1, 2 UNION ALL 
SELECT 3, 3, 1 UNION ALL 
SELECT 4, 2, 3 UNION ALL 
SELECT 5, 2, 4 UNION ALL 
SELECT 6, 1, 5 

DECLARE @Group TABLE(ID INT, Name VARCHAR(100)) 
INSERT INTO @Group 
SELECT 1, 'American' UNION ALL 
SELECT 2, 'Asian' UNION ALL 
SELECT 3, 'European' UNION ALL 
SELECT 4, 'Old' UNION ALL 
SELECT 5, 'Fast' 

然後查詢:

SELECT 
    Product.ID, 
    Product.Name, 
    STUFF 
      (
      (
       SELECT 
        ',' + Groups.Name 
       FROM 
        @ProductGroup AS ProductGroup 
        JOIN @Group AS Groups 
         ON ProductGroup.GroupID=Groups.ID 
       WHERE 
        ProductGroup.ProductID = Product.ID 
       FOR XML PATH('') 
      ),1,1,'') AS Names 
FROM 
    @Product AS Product 
+0

根本沒有。我在你發佈你之前閱讀了這個問題。張貼我的答案,然後我看到你有幾乎相同的答案。然後我投票給你 – Arion 2012-02-09 09:28:35

+0

沒關係,只是嗡嗡... – 2012-02-09 09:29:35