基于另一列连接在一列中

时间:2012-02-09 08:52:48

标签: sql sql-server

我正在使用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"

我该怎么做?

我在客户端使用分页,所以我无法将页面分组。

感谢您的帮助,

百里

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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