删除记录的前5%

时间:2019-02-21 18:34:35

标签: sql-server

我有以下代码,我想删除Triage_To_Dr_Sees_Adjust数字变量的前5%记录。这是否有可能(我知道使用Select TOP(95) Percent会给我最高的95%,但我想反过来,我希望最低的95%)?谢谢!

更新:我在下面的答案中包含了代码,现在我的问题是此代码不产生任何记录。

use EMTCQIData

DECLARE @StartDate Date
DECLARE @EndDate Date

Set @StartDate = '05/01/2017'
Set @EndDate = '12/31/2018'


SELECT sub.*
    FROM (
    Select *,
    Format([CHECKIN_DATE_TIME],'dddd') AS Checkin_Day,  
    CONVERT(VARCHAR(10),[CHECKIN_DATE_TIME],111) as Checkin_date, 
    CONVERT(VARCHAR(20),[CHECKIN_DATE_TIME],108) as Checkin_Time, 
    Case when TRIAGE_TO_DR_SEES < 0 then 0 else TRIAGE_TO_DR_SEES end as 
    TRIAGE_TO_DR_SEES_ADJUST 
    FROM ED_TAT_MASTER
    WHERE 
    (CHECKIN_DATE_TIME > @StartDate and CHECKIN_DATE_TIME < @EndDate) 
    AND (TRIAGE_DATE_TIME not like '')
    AND (TRIAGE_TO_DR_SEES not like '%no%')
    AND (TRACK_GROUP='ED Tracking Group') 
    AND (FORMAT([CHECKIN_DATE_TIME], 'dddd') = 'Sunday') 
    AND CHECKIN_DATE_TIME not like '%2017-07-02%' 
    AND CHECKIN_DATE_TIME not like '%2017-12-24%'
    AND CHECKIN_DATE_TIME not like '%2018-06-10%'
) sub

WHERE sub.TRIAGE_TO_DR_SEES not in (select top(5) Percent sub.TRIAGE_TO_DR_SEES
FROM ED_TAT_MASTER
ORDER BY CHECKIN_DATE_TIME)

2 个答案:

答案 0 :(得分:7)

这将在子查询中获取前5%的内容,然后在主查询中获取其他所有内容。因此,在子查询中添加5%的逻辑,然后外部查询将为您提供其他所有功能。

SELECT *
FROM TableName
WHERE TableIdentity NOT IN (
    SELECT TOP (5) PERCENT TableIdentity
    FROM TableName
    ORDER BY TableIdentity (OR whatever logic you want)
)

答案 1 :(得分:4)

如评论中所述,“最后”的95%只是“第一”的95%,因此只需反转@IsString() lastName: string; @ValidateNested() @Type(() => Address) address: Address 。如果数据的“最终”顺序那么重要,则可以将其包装在子查询中:

ORDER BY

这将按数字顺序返回数字51-1000,也就是“最后一个” 95%。

对于您的查询,在Pseudo-SQL中,它将是:

--Generate some sample data (numbers 1 to 1000)
WITH N AS (
    SELECT N
    FROM (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL))V(N)),
Tally AS(
    SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS I
    FROM N N1
         CROSS JOIN N N2
         CROSS JOIN N N3)
--The solution
SELECT I
FROM (SELECT TOP (95) PERCENT I
      FROM Tally
      ORDER BY I DESC) T
ORDER BY I ASC;