sql - 按行排除满足特定条件的记录
问题描述
我需要一些头脑风暴。我建立了一个查询,向我展示我需要什么。但是,现在的要求是使用此记录列表并根据特定标准排除记录。
这是我当前构建的查询的输出:
Patient | Action | Date
james | REG | 2019/01/01
James | CUR | 2019/01/15
Jacon | REG | 2019/01/12
Jacob | REG | 2019/01/13
Main | CUR | 2019/01/01
Main | REG | 2019/01/05
Lucy | REG | 2019/01/08
Lucy | CUR | 2019/01/09
Lucy | CUR | 2019/01/10
根据上面的示例数据,我想删除第一条记录为“REG”且以下操作为“CUR”的任何患者。所以在这个例子中,我只想删除 James。
关于我应该做什么的任何想法?
感谢您的帮助!
解决方案
您可以使用LEAD功能向前看。
CREATE TABLE #Patients (
ID int IDENTITY(1,1),
Patient varchar(50),
[Action] varchar(50)
);
INSERT INTO #Patients (Patient, [Action])
VALUES
('james', 'REG'),
('James', 'CUR'),
('Jacon', 'REG'),
('Jacob', 'REG'),
('Main', 'CUR'),
('Main', 'REG'),
('Lucy', 'REG'),
('Lucy', 'CUR'),
('Lucy', 'CUR');
SELECT * FROM #Patients;
WITH
PatientWithNextAction AS (
SELECT
Patient,
[Action],
LEAD([Action]) OVER(PARTITION BY Patient ORDER BY ID) NextAction
FROM
#Patients
)
DELETE
FROM
#Patients
WHERE
Patient IN (
SELECT
Patient
FROM
PatientWithNextAction
WHERE
[Action] = 'REG'
AND NextAction = 'CUR'
);
SELECT * FROM #Patients;
DROP TABLE #Patients;
推荐阅读
- c++ - 访问者模式是否比受控使用 RTTI 更好?
- typescript - Webstorm+TypeScript 无法解析 CRA 项目中的 SCSS 模块(错误 TS2339)
- javascript - NodeJS API 不会删除或更新 mongodb 中的数据
- c# - 当 WPF 中的文本太长时,带有滑块的 TextBlock
- sql - SQL Server 错误操作数类型冲突:int 与日期不兼容
- azure-resource-manager - Azure 门户是否使用未记录的 ARM 功能来部署应用服务?
- tensorflow - keras模型预测只有一和零而不是概率
- javascript - 按升序排序但在javascript中保持最高?
- azure - 从 Azure Function 存储访问令牌
- r - 创建一个变量并将一个函数应用到另一个变量