I have the table with rows:
ID CountryCode Status
----------- ----------- -----------
2 PL 1
3 PL 2
4 EN 1
5 EN 1
and by the query
SELECT *
FROM [TestTable]
WHERE Status = 1 AND CountryCode NOT IN (SELECT CountryCode
FROM [TestTable]
WHERE Status != 1)
I get all countrycodes which hasn’t status value = 2
ID CountryCode Status
----------- ----------- -----------
4 EN 1
5 EN 1
I feel that this query could be more simpler and clearer.
How can I change it?
Best regards
EDIT
PL can’t be in result because has a record with status 2
EDIT
Script to create and fill table:
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
)
First: Never use
SELECT *in often used code. Especially in production. Call out your columns.Soap-Box over.
Note: i haven’t tried this, and I don’t currently have the management studio installed, so I can’t test it. But I think you want something like this:
At the least, you’ve got the right idea: if you only want the CountryCodes which do not (on any record) correspond to Status = 2, you need to get everything with status 1, and then exclude any existing rows with have a matching row with status 2. I may have the specific syntax for Not Exists incorrect, though.