Sql 在另一列中选择同时具有NULL和Value(非NULL)的ID

Sql 在另一列中选择同时具有NULL和Value(非NULL)的ID,sql,sql-server,Sql,Sql Server,如何选择在同一表的不同列中同时具有NULL和NOTNULL值的ID 表: Col1 | Col2 abc |空 abc | 123 bcd | 456 结果 Col1 | Col2 abc |空 abc | 123您可以使用isnull函数 像这样 where isnull(col1,0)=isnull(col2,0) 试试这个: select Col1 from mytable group by Col1 having count(case when col1 is null then 1

如何选择在同一表的不同列中同时具有NULL和NOTNULL值的ID

表: Col1 | Col2 abc |空 abc | 123 bcd | 456

结果 Col1 | Col2 abc |空
abc | 123

您可以使用isnull函数

像这样

where isnull(col1,0)=isnull(col2,0)
试试这个:

select Col1 
from mytable
group by Col1
having count(case when col1 is null then 1 end) > 0 and
       count(case when col1 is not null then 1 end) > 0

这将选择与NULL和NOT NULL col2值相关的Col1值。

我不确定您在问什么

是否希望相同行中的两个字段具有相同值的行,无论是否为空

SELECT *
FROM SomeTable 
WHERE EXISTS (SELECT col1 INTERSECT SELECT col2)
范例

或者,如果希望值存在于另一列的任何行中,则使用其他方法

SELECT col1 FROM SomeTable
INTERSECT
SELECT col2 FROM SomeTable

这两种方法都有效,因为INTERSECT在内部使用IS逻辑而不是=。有关更多信息,请参见。请参见,如果在查询中使用标识列或行编号,则非常简单

Declare @table table (id int identity(1,1)
,Col1 varchar(50),Col2 varchar(50))
insert into @table
values
('abc', NULL )
,('abc', '123')
,('bcd' ,'456')


select a.col1,a.col2
from @table A
inner join @table b on a.col1=b.col1 and a.id<>b.id

声明@table col1 nvarchar10, col2整数 插入@table 可乐 价值观 “abc”

插入@table col1,col2 价值观 “abc”,123, “bcd”,456年

从col1所在的@table中选择col1、col2 选择col1 从…起 选择col1, sumcase当col2为null时,则1或0结束为null, sumcase当col2不为null时,则1或0结束为notnulls 来自@table 根据col1分组 s 其中null为0,notnull为0

有了这些数据,预期的结果是什么?也许您应该添加更多的行示例数据,以使事情更加清楚。
;with CTE as
(
select a.col1,a.col2,row_number()over(order by col1) rn
from @table A
)
select a.col1,a.col2
from CTE A
inner join CTE b on a.col1=b.col1 and a.rn<>b.rn