Home Forums SQL Server 2008 T-SQL (SS2K8) SQL Queries for geting common values and uncommon values RE: SQL Queries for geting common values and uncommon values

  • Based on what I can make of your post I think you are looking for this:

    --sample data

    DECLARE @x TABLE (id int not null, value char(1) not null, primary key(id,value));

    INSERT INTO @x SELECT 1,'A' UNION ALL SELECT 1,'B' UNION ALL SELECT 2,'A' UNION ALL SELECT 2,'C' UNION ALL

    SELECT 2,'B' UNION ALL SELECT 3,'A' UNION ALL SELECT 3,'B' UNION ALL SELECT 3,'C' UNION ALL SELECT 3,'D';

    -- common factors

    SELECT value FROM (

    SELECT value, COUNT(value) AS x

    FROM @x

    GROUP BY value

    HAVING COUNT(value)=(SELECT COUNT(DISTINCT id) FROM @x)) AS x

    -- uncommon factors

    SELECT value FROM (

    SELECT value, COUNT(value) AS xx

    FROM @x

    GROUP BY value

    HAVING COUNT(value)<(SELECT COUNT(DISTINCT id) FROM @x)) AS xx

    "I cant stress enough the importance of switching from a sequential files mindset to set-based thinking. After you make the switch, you can spend your time tuning and optimizing your queries instead of maintaining lengthy, poor-performing code."

    -- Itzik Ben-Gan 2001