这是我之前提出的一个问题:A little fuzzy on getting DISTINCT on one column?
在给定数据的情况下,此查询更有意义:
SELECT Receipts.ReceiptID, FolderLink.ReceiptFolderID
FROM dbo.tbl_ReceiptFolderLnk AS FolderLink INNER JOIN
dbo.tbl_Receipt AS Receipts ON FolderLink.ReceiptID = Receipts.ReceiptID
结果:
ReceiptID ReceiptFolderID NewColumn (duplicate folder ID list)
-------------------- --------------- ----------
1 3
2 3
3 7
4 <---> 4 8,9
5 4
6 1
3 8
4 <---> 8 4,9
4 <---> 9 4,8
这个答案让我看到了不同的(ReceiptID)......很棒。现在,对于那些ID,3和4,它们存在于多个ReceiptFolderID中。
鉴于这个非唯一的ReceiptID列表,我想要一个额外的列,逗号分隔的ReceiptFolderLinkID,其中ReceiptID也存在。
因此,对于ReceiptID = 4,新列,例如DuplicateFoldersList,应该读取,“8,9”等,ID = 3,或任何其他重复项。
所以基本上,我想要另一列来指示ReceiptFolderID在其他文件夹中额外出现的ReceiptID。
谢谢!
答案 0 :(得分:1)
您可以创建一个函数,给定ReceiptID和该行的“当前”ReceiptFolderID,将其他ReceiptFolderID作为连接的逗号分隔列表返回。例如:
CREATE FUNCTION [dbo].[GetOtherReceiptFolderIDs](@receiptID int, @receiptFolderID int)
RETURNS varchar(MAX) AS
BEGIN
DECLARE @returnValue varchar(MAX)
SELECT @returnValue = COALESCE(@returnValue + ', ', '') + COALESCE(CONVERT(varchar(MAX), ReceiptFolderID), '')
FROM tbl_ReceiptFolderLink AS FolderLink
WHERE FolderLink.ReceiptID = @receiptID
AND FolderLink.ReceiptFolderID <> @receiptFolderID
RETURN @returnValue
END
然后,您可以运行使用此函数的查询来获取新列:
SELECT Receipts.ReceiptID, ReceiptFolderID, dbo.GetOtherReceiptFolderIDs(Receipts.ReceiptID, ReceiptFolderID) AS NewColumn
FROM tbl_Receipt AS Receipts
INNER JOIN tbl_ReceiptFolderLink AS FolderLinks
ON Receipts.ReceiptID = FolderLinks.ReceiptID
我对此进行了测试,并产生了以下结果(如果我的模式正确的话):
ReceiptID ReceiptFolderID NewColumn
6 1 NULL
1 3 NULL
2 3 NULL
4 4 8, 9
5 4 NULL
3 7 8
3 8 7
4 8 4, 9
4 9 4, 8
答案 1 :(得分:0)
在Mysql中有group_concat聚合函数,但在T-SQL和oracle中你需要使用另一种方法... This site列出了多种T-SQL方法,但没有一种非常简单易行(如mysql)是)