如何使用 SQL 查询查看带有 group by 子句的逗号分隔字符串中的列值?
How to view a column values in comma separated string with group by clause using SQL query?
如何在以下 SQL 查询(在 SQL Server 2014 中)中获取带有逗号分隔字符串的 U_ProductType 列。它需要按 DocNum 分组,并且在转换为逗号分隔字符串时不需要 U_ProductType 中的 Null 值。我也尝试了“FOR XML PATH”选项。这是我的查询供您参考,
SELECT
ORDR.DocNum, ORDR.CardCode, ORDR.CardName, ORDR.SlpCode,
OSLP.SlpName, OITM.U_Product_Type,
SUM (RDR1.LineTotal) LineTotal,
ISNULL (SUM (DPI1.LineTotal), 0) dwpnt
FROM
ORDR
INNER JOIN
RDR1 ON RDR1.DocEntry = ORDR.DocEntry
LEFT JOIN
OITM ON OITM.ItemCode = RDR1.ItemCode
LEFT JOIN
OSLP ON OSLP.SlpCode = ORDR.SlpCode
LEFT JOIN
DPI1 ON DPI1.BaseEntry = RDR1.DocEntry
AND DPI1.TargetType <> 14
AND DPI1.BaseLine = RDR1.LineNum
LEFT JOIN
RCT2 ON RCT2.DocEntry = DPI1.DocEntry
LEFT JOIN
ORCT ON RCT2.DocNum = ORCT.DocEntry AND ORCT.Canceled = 'N'
WHERE
ORDR.CANCELED = 'N'
AND ISNULL (DPI1.LineTotal, 0) = 0
AND ORDR.SlpCode = 67
GROUP BY
ORDR.DocNum, ORDR.CardCode, ORDR.CardName, ORDR.SlpCode,
OSLP.SlpName, OITM.U_Product_Type
结果和我的要求如下,
您可以使用 STUFF()
,如下所示。只需将 cte
替换为您的原始查询即可。另一种方法是用您当前的结果创建一个临时文件 table,并将 cte
替换为新创建的临时文件 table。
SELECT DoNum
, CardCode
, CardName
, SipCode
, SlpName
, STUFF((SELECT DISTINCT ',' + CONVERT(VARCHAR,U_Product_Type)
FROM [cte] t1
WHERE (DoNum = cte.DoNum
and CardCode = t1.CardCode
and CardName = t1.CardName
and SipCode = t1.SipCode
and SlpName = t1.SlpName)
FOR XML PATH ('')), 1, 2, '') AS U_Product_Type
,sum(LineTotal) as LineTotal
,sum(dwpnt) as dwpnt
FROM cte
group by DoNum
, CardCode
, CardName
, SipCode
, SlpName
如何在以下 SQL 查询(在 SQL Server 2014 中)中获取带有逗号分隔字符串的 U_ProductType 列。它需要按 DocNum 分组,并且在转换为逗号分隔字符串时不需要 U_ProductType 中的 Null 值。我也尝试了“FOR XML PATH”选项。这是我的查询供您参考,
SELECT
ORDR.DocNum, ORDR.CardCode, ORDR.CardName, ORDR.SlpCode,
OSLP.SlpName, OITM.U_Product_Type,
SUM (RDR1.LineTotal) LineTotal,
ISNULL (SUM (DPI1.LineTotal), 0) dwpnt
FROM
ORDR
INNER JOIN
RDR1 ON RDR1.DocEntry = ORDR.DocEntry
LEFT JOIN
OITM ON OITM.ItemCode = RDR1.ItemCode
LEFT JOIN
OSLP ON OSLP.SlpCode = ORDR.SlpCode
LEFT JOIN
DPI1 ON DPI1.BaseEntry = RDR1.DocEntry
AND DPI1.TargetType <> 14
AND DPI1.BaseLine = RDR1.LineNum
LEFT JOIN
RCT2 ON RCT2.DocEntry = DPI1.DocEntry
LEFT JOIN
ORCT ON RCT2.DocNum = ORCT.DocEntry AND ORCT.Canceled = 'N'
WHERE
ORDR.CANCELED = 'N'
AND ISNULL (DPI1.LineTotal, 0) = 0
AND ORDR.SlpCode = 67
GROUP BY
ORDR.DocNum, ORDR.CardCode, ORDR.CardName, ORDR.SlpCode,
OSLP.SlpName, OITM.U_Product_Type
结果和我的要求如下,
您可以使用 STUFF()
,如下所示。只需将 cte
替换为您的原始查询即可。另一种方法是用您当前的结果创建一个临时文件 table,并将 cte
替换为新创建的临时文件 table。
SELECT DoNum
, CardCode
, CardName
, SipCode
, SlpName
, STUFF((SELECT DISTINCT ',' + CONVERT(VARCHAR,U_Product_Type)
FROM [cte] t1
WHERE (DoNum = cte.DoNum
and CardCode = t1.CardCode
and CardName = t1.CardName
and SipCode = t1.SipCode
and SlpName = t1.SlpName)
FOR XML PATH ('')), 1, 2, '') AS U_Product_Type
,sum(LineTotal) as LineTotal
,sum(dwpnt) as dwpnt
FROM cte
group by DoNum
, CardCode
, CardName
, SipCode
, SlpName