SQL查询单个表,具有相同标识

时间:2016-04-06 19:31:55

标签: sql sql-server

我在SQL 2012中有一个表,它有多行用于相同的ID,如下所示:

ID       Company       Item     
123456   CompanyA      Item1
123456   CompanyA      Item2
456123   CompanyB      Item2
789123   CompanyC      Item1 

每个ID / Company在此表中可以有多行。我需要查询表并显示没有ItemX的任何记录,还要忽略该公司的任何其他记录?所以在这个例子中,ID为123456的CompanyA有Item1和Item2,但我不想看到Item2,所以我需要我的结果如下:

ID       Company       Item     
789123   CompanyC      Item1 

感谢。

杰森

6 个答案:

答案 0 :(得分:1)

DECLARE @ItemToExclude AS VARCHAR(10)
SET @ItemToExclude = 'Item2'

SELECT A.id, A.Company,A.Item
FROM <table> A
WHERE Item <> @ItemToExclude -- Find IDs that Do Not Have the ItemToExclude
AND id NOT IN --AND That Do Not have entries with the Item to Exclude
(
SELECT id
FROM <table> X
WHERE Item = @ItemToExclude
)

答案 1 :(得分:0)

您可能希望在where子句中使用and 所以查询就像

SELECT * FROM table WHERE ID='789123' and Item='Item1'

答案 2 :(得分:0)

这样的事情可能就是你想要的:

with singleIDs as (
select id, count(*) records
from theTable
group by id
having count(*) = 1)

select yourFields
from theTable join singleIDs on theTable.Id = singleIDs.id

答案 3 :(得分:0)

像这种查询之类的东西可以获得预期的输出。

SELECT A.Id,A.CompanyId, A.Item
FROM CompanyTable A
INNER JOIN CompanyTable A1 ON A.ID = A1.ID AND A1.Item <> 'Item1'
INNER JOIN CompanyTable A2 ON A.ID = A2.ID AND A2.Item = 'Item2'

答案 4 :(得分:0)

SELECT  *
FROM    [Table] t1
WHERE   NOT EXISTS ( SELECT 1
                     FROM   [Table] t2
                     WHERE  t1.ID = t2.ID
                            AND t2.Item = 'Item2' )

答案 5 :(得分:0)

您正在寻找Left Excluding JOIN 您的表格和(包含所有&#39; Item2&#39;)行的表格:

使用此输入:

create table t (id int, company char(10), item char(10));
insert into t (id,company,item)
    values 
    (123456,'CompanyA','Item1'),
    (123456,'CompanyA','Item2'),
    (456123,'CompanyB','Item2'),
    (789123,'CompanyC','Item1');

以下查询(这是答案):

select t.id, t.company, t.item
  from t
  left join (select id from t where item='Item2') t2
    on t.id=t2.id
 where t2.id is null;

给出

+--------+----------+-------+
| id     | company  | item  |
+--------+----------+-------+
| 789123 | CompanyC | Item1 |
+--------+----------+-------+
1 row in set (0.00 sec)

好的,这是MySQL,但我认为SQL Server也是这样。

参考我提供的链接,在这种情况下,表格A(左侧)是您的完整表格和表格B(另一个)包含item='Item2'的所有ID 。如果你只是left join他们,你会得到:

mysql> select t.id, t.company, t.item, t2.id as id2
         from t
         left join (select id from t where item='Item2') t2
           on t.id=t2.id;

+--------+----------+-------+--------+
| id     | company  | item  | id2    |
+--------+----------+-------+--------+
| 123456 | CompanyA | Item1 | 123456 |
| 123456 | CompanyA | Item2 | 123456 |
| 456123 | CompanyB | Item2 | 456123 |
| 789123 | CompanyC | Item1 |   NULL |
+--------+----------+-------+--------+
4 rows in set (0.00 sec)

因为对于最后一行,第二个表中没有item='Item2'的行。 因此,我们添加where t2.id is null并仅获得所需的行。