我有这些列的表Customer
:
sales_ID varchar(50)
product_ID int
ProcessNumber int
CreateDate datetime
以及此示例数据:
sales_Id product_id ProcessNumber
---------------------------------------------
00000020041 1733 15
00000020041 1733 15
00000020041 1733 15
1522 1111 11
1522 1111 11
76002 1333 45
76002 1333 45
问题:
如果我使用此查询
SELECT *
FROM
(SELECT
*,
CountOfRowsInGroup = COUNT(*) OVER (PARTITION BY sales_Id, product_ID, ProcessNumber)
FROM Customer) AS tbl
WHERE
CountOfRowsInGroup > 1
ORDER BY
Sales_ID;
查询结果:
sales_Id product_id ProcessNumber
---------------------------------------------
00000020041 1733 15
00000020041 1733 15
00000020041 1733 15
1522 1111 11
1522 1111 11
76002 1333 45
76002 1333 45
但是我希望结果显示此结果的重复行,如下所示
sales_Id product_id ProcessNumber
---------------------------------------------
DUPLICATED ROW
00000020041 1733 15
00000020041 1733 15
00000020041 1733 15
DUPLICATED ROW
1522 1111 11
1522 1111 11
DUPLICATED ROW
76002 1333 45
76002 1333 45
由于
答案 0 :(得分:3)
从您获得的查询结果中,您可以附加以下查询以获得所需的输出。在这里,我将排名设为DENSE_RANK
,以获得每个sales_id
的唯一ID。对于DUPLICATE ROW
值,排名将为1,2,3
等,对于现有值,排名将按1.1,2.1,3.1
等顺序排列。
然后我使用UNION ALL
来合并现有值的结果和DUPLICATE ROW
,而ORDER BY
将采用格式1,1.2,2,2.1 ....
等。
;WITH CTE AS
(
SELECT DENSE_RANK() OVER(ORDER BY sales_Id)+0.1 RNO,
DENSE_RANK() OVER(ORDER BY sales_Id) RNO2,'DUPLICATE ROW' DUP,*
FROM #TEMP
)
,CTE2 AS
(
SELECT DISTINCT RNO2 AS ROWNUM,CAST(DUP AS VARCHAR(30)) sales_Id ,NULL product_id,NULL ProcessNumber
FROM CTE
UNION ALL
SELECT RNO,CAST(sales_Id AS VARCHAR(30)),product_id,ProcessNumber
FROM CTE
)
SELECT sales_Id,product_id,ProcessNumber
FROM CTE2
ORDER BY ROWNUM
请注意,我创建的表格是您问题中的示例查询的结果。你需要把它们结合起来。