0

我有一个包含vendor,category和的表page。我需要根据这个表创建一个索引(就像你在目录中一样)。

我可以通过遍历行在 Excel 中执行此操作,如果供应商和类别与上面的行相同,则新页面将添加到其上方单元格的末尾:

Tim's Company      Code     120
Tim's Company      Code     122

会导致

Tim's Company      Code     120,122

当我处理 1000 行以下时,Excel 很好。我在这里的12K区域。这将需要永远。另外,我最终得到了一些我不想要的页面重复实例。在SQL我可以预先消除重复项时,我不确定如何在页面上进行连接。我会更好地这样做SSRS吗?还是视图也会产生结果?

4

3 回答 3

1
DECLARE @x TABLE(vendor varchar(32), category varchar(32), page int);

INSERT @x VALUES
('Tim''s Company','Code',120),
('Tim''s Company','Code',122);

SELECT vendor, category, pages = STUFF((
  SELECT ',' + CONVERT(varchar(11), page)
  FROM @x AS x2
  WHERE x2.vendor = x.vendor AND x2.category = x.category
  ORDER BY page
  FOR XML PATH(''), 
  TYPE).value(N'./text()[1]', N'nvarchar(max)'),1,1,'')
FROM @x AS x
GROUP BY vendor, category;
于 2013-08-29T15:28:03.240 回答
0

试试这个:小提琴演示

SELECT t1.Vendor,t1.Category,
       csvPages = REPLACE( (SELECT CONVERT(VARCHAR(12),Page) AS [data()]
                            FROM mytable t2
                            WHERE t2.Vendor = t1.Vendor AND 
                                  t2.Category = t1.Category
                            ORDER BY t2.Vendor
                            FOR XML PATH('')
                           ), ' ', ',')
FROM mytable t1
GROUP BY t1.Vendor,t1.Category ;
于 2013-08-29T15:28:12.597 回答
0

您可以创建一个将所有值连接到标量值的函数:

CREATE FUNCTION [dbo].[getPages]
(
    @Vendor varchar(100),
    @Category varchar(50)
)
RETURNS VARCHAR(8000)
AS
BEGIN
    DECLARE @Pages VARCHAR(8000) 
    SELECT @Pages = COALESCE(@Pages + ',','') +  CAST(TN.Page AS VARCHAR)
    FROM dbo.TableName TN
    WHERE TN.Vendor=@Vendor AND TN.Category=@Category
    ORDER BY TN.Page
    RETURN @Pages
END

现在你可以这样使用它:

SELECT Vendor, Category, 
       Pages=dbo.getPages(Vendor,Category)
FROM dbo.TableName
GROUP BY Vendor, Category

DEMO

VENDOR          CATEGORY        PAGES
Tims Company    Code            120,122
于 2013-08-29T15:35:17.437 回答