Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Select Rows Based on Entire 'Subset' Matching Condition

$
0
0

Hi All,

Using SQL Server 2008 R2.  Below is DDL and Sample Data:

CREATE TABLE [dbo].[Sample](
    [SampleID] [varchar](50) NOT NULL,
    [Description] [varchar](50) NULL
GO

CREATE TABLE [dbo].[SampleDetailID](
    [SampleDetailID] [varchar](50) NOT NULL,
    [SampleID] [varchar](50) NULL,    
    [Approved] [bit] NULL
GO

INSERT INTO [dbo].[Sample]
    ([SampleID], [Description])
VALUES
    ('A1', 'Test 1'),
    ('A2', 'Test 2'),
    ('A3', 'Test 3'),
    ('A4', 'Test 4')

INSERT INTO [dbo].[SampleDetails]
    ([SampleDetailID], [SampleID], [Approved])
VALUES
    ('B1', 'A1', '1'),
    ('B2', 'A1', '0'),
    ('B3', 'A1', '0'),
    ('B4', 'A2', '0'),
    ('B5', 'A3', '1'),
    ('B6', 'A3', '1'),
    ('B7', 'A4', '1'),
    ('B8', 'A4', '1'),
    ('B9', 'A4', '0')

Using the above example, I am looking to return only those rows from the parent table which have all joined rows (B.SampleID = A.SampleID) (where B is SampleDetails and A is Sample) in the child table that satisfy the condition (Approved = 1).  So the expected output would be:

SampleID    Description
--------    -----------
A3        Test 3

As A3 is the only row in Sample that has Approved = 1 for every one of its rows in SampleDetails.  Additionally (just in case it's worth mentioning) per the sample data above the number of rows in SampleDetails for a given Sample may not always be consistent.  Sometimes there may be one, othertimes there may be three or more.

Any help with this is greatly appreciated!

Best Regards

Brad


Viewing all articles
Browse latest Browse all 23857

Trending Articles