选择列表中的SQL标签
我的表格中有以下行,显示了患者(作为PatientCon)、疾病和标签(0 | 1作为serviceInterupt) 如果患者同时具有0标签和1标签,则结果中可能有多行选择列表中的SQL标签,sql,subquery,Sql,Subquery,我的表格中有以下行,显示了患者(作为PatientCon)、疾病和标签(0 | 1作为serviceInterupt) 如果患者同时具有0标签和1标签,则结果中可能有多行 ServiceInterrupt Disease PatientCon 0 d1 1111 0 d1 1112 1 d1 1112 0 d1
ServiceInterrupt Disease PatientCon
0 d1 1111
0 d1 1112
1 d1 1112
0 d1 1113
0 d1 1114
1 d1 1114
1 d1 1115
我想要的是添加一个带有标签的新列(Active | Not Active as NewLabel),
显示患者是否至少有一行serviceInterrupt=1
ServiceInterrupt Disease PatientCon NewLabel
0 d1 1111 Active
0 d1 1112 Not Active
1 d1 1112 Not Active
0 d1 1113 Active
0 d1 1114 Not Active
1 d1 1114 Not Active
1 d1 1115 Not Active
如何在SQL中实现这一点
编辑:
我用的桌子是
patientConcerned int NOT NULL,
disease ntext NULL,
ServiceInterrupt bit NULL,
使用标准SQL,您可以使用
case
语句和窗口函数执行此操作:
select ServiceInterrupt, Disease, PatientCon,
(case when max(ServiceInterrupt) over (partition by PatientCon) > 0
then 'Not Active'
else 'Active'
end) as newLabel
from table;
如果前面的答案不适合您,请尝试以下方法:
select serviceInterrupt, disease, PatientCon,
(case when exists (select *
from table b
where a.patientCon = b.patientCon
and b.serviceInterrupt = 1)
then 'Active'
else 'Not Active'
end ) as newLabel
from table a;
确切的语法可能会因您使用的SQL引擎而异,因此如果您标记该语法可能会有所帮助。请使用您正在使用的数据库标记您的问题。是否要将该列添加到表中,还是尝试生成一个将显示“新标签”列的查询?抱歉!我们同时发布!:D@Galma88 . . . 哇!我们似乎同时回答了第二个问题。操作数数据类型位对于max运算符无效。这就是我得到的结果。这和我在这里写的一样。我一定是在你编辑的时候写的——在我发布之前没有发现你的编辑。
select serviceInterrupt, disease, PatientCon,
(case when exists (select *
from table b
where a.patientCon = b.patientCon
and b.serviceInterrupt = 1)
then 'Active'
else 'Not Active'
end ) as newLabel
from table a;