【问题标题】:SQL query: selecting only NULL values from a group?SQL 查询:仅从组中选择 NULL 值?
【发布时间】:2015-08-14 13:22:53
【问题描述】:

我正在使用如下所示的数据表:

Names           City            Date        Color    Shape
John Smith      Baltimore       8/1/2015    Blue
John Smith      Baltimore       8/1/2015    Green 
John Smith      Baltimore       8/1/2015             Rectangle
John Smith      Baltimore       8/1/2015
John Smith      Baltimore       8/1/2015             Square
John Smith      Baltimore       8/1/2015
Rob Johnson     Baltimore       8/1/2015
Rob Johnson     Baltimore       8/1/2015
Rob Johnson     Baltimore       8/1/2015
Rob Johnson     Baltimore       8/1/2015
Rob Johnson     Baltimore       8/1/2015
Greg Jackson    Philadelphia    8/1/2015
Greg Jackson    Philadelphia    8/1/2015
Greg Jackson    Philadelphia    8/1/2015
Greg Jackson    Philadelphia    8/1/2015             Circle
Greg Jackson    Philadelphia    8/1/2015
Tom Green       Philadelphia    8/1/2015
Tom Green       Philadelphia    8/1/2015
Tom Green       Philadelphia    8/1/2015    Red
Tom Green       Philadelphia    8/1/2015
Tom Green       Philadelphia    8/1/2015        

我的查询目标是选择所有存在的五种数据类型,但要隔离 Names 字段中在 Color 和 Shape 字段中具有 NULL 值的那些值。我正在 MS Access 中编写此 SQL。到目前为止,我的查询如下所示:

SELECT [Names], [City], [Date], [Color], [Shape]
FROM [databasename]
WHERE 
 (
  ([Color] IS NULL)
   AND
  ([Shape] IS NULL)
 );

从示例数据表中,我希望结果仅包括 Rob Johnson,因为与该名称条目关联的所有行的颜色和形状字段都具有 NULL 值。但是,通过此查询,我还获得了所有其他名称,并返回了 Color 和 Shape 字段中具有 NULL 值的特定行。

因此,预期的输出将如下所示:

Names           City            Date        Color    Shape
Rob Johnson     Baltimore       8/1/2015

我怀疑我需要在这里使用 GROUP 运算符,但我不太确定该怎么做。有什么想法吗?

【问题讨论】:

  • 你能添加你的预期输出吗?

标签: sql ms-access-2010


【解决方案1】:

我想你想要这个:

 SELECT 
    DISTINCT [Names], [City], [Date], [Color], [Shape]
 FROM [table]
 WHERE [Names] NOT IN (
    SELECT [Names] FROM [table] WHERE ([Color] IS NOT NULL) OR 
                                      ([Shape] IS NOT NULL)
 ); 

可以通过其他方式完成,但这应该接近您的原始查询。

【讨论】:

  • 我认为这需要distinct 否则它将返回 Rob Johnson 5 次。
  • 您可能想要输入distinct,因为 OP 只想要一行。
  • 非常感谢@Mithrandir。这种结构非常适合实际数据集。如果我想在这里使用DISTINCT 运算符,它会在NOT IN ( 嵌套中吗?
  • 没关系,我在编辑后的查询中看到了DISTINCT。我将其添加到我的,结果正是我想要的。再次感谢!
【解决方案2】:

您可以使用聚合和内连接:

SELECT d1.* FROM [database-name] d1
INNER JOIN (
    select Names,MAX(Color) as mc,MAX(Shape) as ms
    from [database-name]
    group by Names
            ) d2
ON d1.Names = d2.Names
WHERE mc IS NULL
AND ms IS NULL

【讨论】:

    猜你喜欢
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-26
    相关资源
    最近更新 更多