简单的重构SQL查询

use*_*618 3 sql refactoring sql-server-2005

我有表行:

ID          CountryCode Status
----------- ----------- -----------
2           PL          1
3           PL          2
4           EN          1
5           EN          1
Run Code Online (Sandbox Code Playgroud)

并通过查询

SELECT *
  FROM [TestTable]
  WHERE Status = 1 AND CountryCode NOT IN (SELECT CountryCode
  FROM [TestTable]
  WHERE Status != 1)
Run Code Online (Sandbox Code Playgroud)

我得到所有没有状态值= 2的国家/地区代码

ID          CountryCode Status
----------- ----------- -----------
4           EN          1
5           EN          1
Run Code Online (Sandbox Code Playgroud)

我觉得这个查询可以更简单,更清晰.

我该怎么改变它?

最好的祝福

编辑

PL不能在结果中因为具有状态2的记录

编辑

用于创建和填充表格的脚本:

USE [DatabaseName]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TestTable](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [CountryCode] [nvarchar](2) NOT NULL,
    [Status] [int] NOT NULL
) ON [PRIMARY]

INSERT INTO dbo.TestTable
          ( CountryCode, Status )
  VALUES  ( 'PL', -- CountryCode - nvarchar(2)
            1  -- Status - int
            )

INSERT INTO dbo.TestTable
          ( CountryCode, Status )
  VALUES  ( 'PL', -- CountryCode - nvarchar(2)
            2  -- Status - int
            )

INSERT INTO dbo.TestTable
          ( CountryCode, Status )
  VALUES  ( 'EN', -- CountryCode - nvarchar(2)
            1  -- Status - int
            )
INSERT INTO dbo.TestTable
          ( CountryCode, Status )
  VALUES  ( 'EN', -- CountryCode - nvarchar(2)
            1  -- Status - int
            )
Run Code Online (Sandbox Code Playgroud)

All*_*enG 7

第一:永远不要使用SELECT *经常使用的代码.特别是在生产中.喊出你的专栏.

肥皂盒结束.

注意:我没有试过这个,我目前没有安装管理工作室,所以我无法测试它.但我认为你想要这样的东西:

Select Id, CountryCode, Status
From [TestTable] t
Where Status <> 2
And Not Exists(select status from [TestTable] t2 
                             where t2.Status = 2 
                             and t2.CountryCode = tt.CountryCode)
Run Code Online (Sandbox Code Playgroud)

至少,你有正确的想法:如果你只想要没有(在任何记录上)的CountryCodes对应于Status = 2,你需要获得状态为1的所有内容,然后排除任何现有行匹配行与状态2.但我可能有不存在的特定语法不正确.