我有一个重复值的数据库。特别是SiteCode,LastName,FirstName,DateofService,Payer,BilledAmount,NetReceivable和ContractualDiscount连接以形成在整个表中重复出现的记录。
我想删除这些字段中除了一个实例之外的所有实例,并且我只想选择一个NetBilledHistoryID(这是表中每条记录的唯一字段)。
不幸的是,当我运行此查询时,仍然会获得重复的值。
如何更正此问题,以便我的选择查询消除这些重复项?或者,更好的是,我是否应该一起使用不同的查询技术?
SELECT *
FROM [Reports].[dbo].[NetBilledHistory] t1
WHERE EXISTS (
SELECT 1 FROM [Reports].[dbo].[NetBilledHistory] AS t2
WHERE t2.SiteCode = t1.SiteCode
AND t2.LastName = t1.LastName
AND t2.FirstName = t1.FirstName
AND t2.DateofService = t1.DateofService
AND t2.Payer = t1.Payer
AND t2.BilledAmount = t1.BilledAmount
AND t2.NetReceivable = t1.NetReceivable
AND t2.ContractualDiscount = t1.ContractualDiscount
AND t2.NetBilledHistoryID < t1.NetBilledHistoryID)
答案 0 :(得分:0)
您可以使用CTE
:
WITH cte_query AS (
SELECT ROW_NUMBER() OVER(
partition by SiteCode, LastName, FirstName,
DateofService, Payer, BilledAmount, NetReceivable,
ContractualDiscount
order by NetBilledHistoryID) AS RowNum, *
FROM [Reports].[dbo].[NetBilledHistory]
)
SELECT * FROM cte_query where RowNum = 1;
根据需要进行调整以适合您的列等目的。