当我参加面试时,我遇到了一个有趣的问题,如下所列 下面给出问题
How to find out the occurrence of the value 1 in all the columns
DECLARE @tbl AS TABLE(Col1 INT, Col2 INT, Col3 INT)
INSERT INTO @tbl
VALUES(1,1,1),(1,2,1),(1,1,3)
我已经分享了如下答案。不确定这是否是正确的答案。
SELECT (SELECT COUNT(1) FROM @tbl WHERE COL1 = 1) +
(SELECT COUNT(1) FROM @tbl WHERE COL2 = 1)+
(SELECT COUNT(1) FROM @tbl WHERE COL3 = 1)
请告诉我是否有任何其他方法可以找到正确的答案
最佳答案
您可以使用应用
:
select cols, count(*) as occurrence
from @tbl cross apply
( values ('col1', col1), ('col2', col2), ('col3', col3)
) t (cols, val)
where val = 1
group by cols;
关于sql - 如何使用查询在不同列中查找相同值的出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51282876/