如果行仅包含一个值,请选择行

时间:2019-08-12 05:30:17

标签: sql sql-server group-by having-clause

我正在尝试查找在Col J到Col L中所有具有空值的行

我的输出应如下所示(绿色是我所期望的,其他应该忽略):

enter image description here 我尝试了下面的代码,但是没有用:

-- Step 1 get all the data as required

select Col A,   Col B,  Col C,  Col D,  Col E,  Col F,  Col G,  Col H,  Col I,  Col J,  Col K,  Col L,
into tempDB
from MainDB

-- Step 2
select ColB, min(Col C) , min(Col D), min(Col E), min(Col F)
from tempDB 
where Col J = Col K and Col L = null
group by Col B

6 个答案:

答案 0 :(得分:2)

我对您的要求的理解是正确的,您希望其中ColJColKColL中所有值均为NULL的行

select  ColB, min(ColC) , min(ColD), min(ColE), min(ColF)
from    tempDB 
group by ColB
having  min(ColJ)   is null
and     min(ColK)   is null
and     min(ColL)   is null

答案 1 :(得分:2)

试试这个-

SELECT ColB, 
MIN(ColC) , MIN(ColD), MIN(ColE), MIN(ColF)
FROM tempDB 
GROUP BY Col B
HEVING SUM(COALESCE (ColJ,0)) = 0
AND SUM(COALESCE (ColK,0)) = 0
AND SUM(COALESCE (ColL,0)) = 0

答案 2 :(得分:1)

您需要使用IS NULL而不是= NULL。您不能比较null是否等于某事物,即使它 null。

SELECT [ColB], MIN([Col C]), MIN([Col D]), MIN([Col E]), MIN([Col F]) 
FROM tempDB 
WHERE [Col J] IS NULL
  AND [Col K] IS NULL
  AND [Col L] IS NULL
GROUP BY [Col B]

答案 3 :(得分:1)

这应该有效。

SELECT *
FROM tempdb
where colj is null and colk is null and coll is null

您不应使用something = null条件,因为 null不是什么,而是 null是未定义的内容。

进一步阅读 https://www.w3schools.com/sql/sql_null_values.asp

编辑:-如果要基于行的colb值

SELECT *
FROM tempdb
where colj is null and colk is null and coll is null and colb=4444

如果数据类型不是数字(char,varchar等),请在4444前后输入”。

答案 4 :(得分:0)

如果要colb,其中coljcolkcoll中的所有行都包含空值:

select ColB, min(ColJ), min(ColK), min(ColL)
from tempDB 
group by ColB
having coalesce(min(ColJ), min(ColK), min(ColL)) is null

答案 5 :(得分:0)

SELECT 
  t.[Col A], 
  t.[Col B], 
  t.[Col C], 
  t.[Col D], 
  t.[Col E],
  t.[Col F],
  t.[Col G],
  t.[Col H],
  t.[Col J],
  t.[Col K],
  t.[Col L]
FROM tempDB t
INNER JOIN
(
  SELECT MIN([Col B]) AS [Col B]
    FROM tempDB
    GROUP BY 
        [Col B]
    HAVING
        MIN([Col J]) IS NULL
        AND MIN([Col K]) IS NULL
        AND MIN([Col L]) IS NULL
) d
  on t.[Col B] = d.[Col B]