我的表格包含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
中做得更好吗?或视图是否会生成结果?
答案 0 :(得分: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(12), page)
FROM @x AS x2
WHERE x2.vendor = x.vendor AND x2.category = x.category
ORDER BY page
FOR XML PATH(''), TYPE).value('.[1]','nvarchar(max)'),1,1,'')
FROM @x AS x
GROUP BY vendor, category;
答案 1 :(得分:0)
试试这个: Fiddle demo
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 ;
答案 2 :(得分: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
VENDOR CATEGORY PAGES
Tims Company Code 120,122