sql - 如何在sql 2008中查询的where子句中使用新定义的列名

标签 sql sql-server sql-server-2008

我在 sql server 2008 中有一个查询,例如:

select t1.Id, 
MatchIds = (select dbo.GetCommaDelimitedString(t2.Id) from #temp t2
       where t1.Id != t2.Id and t1.PatientId=t2.PatientId 
       and t1.HCN=t2.HCN 
      )
from #temp t1

此查询具有如下输出:
Id   MatchIds
1    2,5,6
2    1,5,6
3    null
4    null
5    1,2,6
6    1,2,5

我想要的是摆脱 MatchIds 为空的行。当我尝试添加 MatchIds is not null 时在主查询的 where 子句中,它不接受它说 invalid column name MatchIds并且我不想编写我用来在 where 子句中分配 MatchIds 的相同查询。在这种情况下,提供它的最佳方式是什么?

任何帮助,将不胜感激。

最佳答案

只需将查询移至 CROSS APPLY

select t1.Id, 
       cs.MatchIds
from #temp t1
CROSS APPLY (select dbo.GetCommaDelimitedString(t2.Id) from #temp t2
       where t1.Id != t2.Id and t1.PatientId=t2.PatientId 
       and t1.HCN=t2.HCN) cs (MatchIds)

关于sql - 如何在sql 2008中查询的where子句中使用新定义的列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40659698/

相关文章:

mysql - 在一个表中有三个主键,其中两个是外键是否有意义?

sql - 合并查询中按月和年排序

c# - 如果在 sql server 中回滚事务,它会删除临时表(在事务中创建)吗?

c# - Entity Framework 6 w/DatabaseGenerateOption.Compulated : column does not allow nulls. INSERT 失败

sql - 返回存储过程中 OUTPUT 参数的值

sql-server-2008 - Lotus Domino NotesSQL ODBC 和 SQL 2008 查询

sql - 在 SQL Server 2008 中比较时间

php - 按日期排序并按 ID 分组

SQL 使用值序列更新表列

sql - 关键字段上存在 1 到 3 关系的表之间的差异