有条件地基于字段值的组合返回记录

时间:2011-09-20 17:20:45

标签: sql-server sql-server-2008

我是这个论坛和sql的新手,希望有人能够帮助我。

我正在尝试创建一个查询,该查询将返回除了一个以外的所有字段中具有相同值的记录。

表格中有以下字段:

零件编号|年份|制造商|型号

我想要返回一年(2011年)中可用的所有记录,但不会在另一年(2012年)中提供。例如:

零件编号|年份|制造商|型号
123456 | 2011 |福特|焦点

此记录将返回,因为没有123456 | 2012 |福特|焦点组合。

但是,如果有2012年的记录,我不希望返回任何记录。

零件编号|年份|制造商|型号
123456 | 2011 |福特|焦点
123456 | 2012 |福特|关注

如果存在这种情况,则不应返回任何记录。

我希望我解释得那么好。如果我需要澄清任何要点,请告诉我。

提前致谢!

修改

这看起来不错吗?

SELECT *
FROM [mytable].[dbo].[apps] yt
    WHERE yt.make in (47,54, 48, 59, 3, 42, 21, 67, 1168, 76, 40, 39)
    and yt.model in (432, 2484, 16206, 2487, 6831, 5858, 659, 663, 2816, 688, 668, 670, 6089, 2427, 752, 21, 349, 356, 108, 883, 2440, 16227, 1011, 303, 6867, 110, 440, 975, 286, 287)
    and yt.Year = 2011
        AND NOT EXISTS(SELECT NULL
                           FROM [mytable].[dbo].[apps] yt2
                           WHERE yt.part# = yt2.part#
                               AND yt.make = yt2.make
                               AND yt.model = yt2.model
                               AND yt2.Year = 2012)
order by part#

3 个答案:

答案 0 :(得分:0)

SELECT yt.PartNumber, yt.Year, yt.Make, yt.Model
    FROM YourTable yt
    WHERE yt.Year = 2011
        AND NOT EXISTS(SELECT NULL
                           FROM YourTable yt2
                           WHERE yt.PartNumber = yt2.PartNumber
                               AND yt.Make = yt2.Make
                               AND yt.Model = yt2.Model
                               AND yt2.Year = 2012)

答案 1 :(得分:0)

尝试

SELECT c.PartNumber, c.Year, c.Make, c.Model
FROM Cars c
inner join 
(
    SELECT count(*) [count], PartNumber, Make, Model
    from cars
    GROUP BY PartNumber, Make, Model
    HAVING count(*) = 1
) as g 
ON c.PartNumber = g.PartNumber and c.Make = g.Make and c.Model = g.Model

使用此设置代码

create table Cars
(partnumber nvarchar(20), [year] int, make nvarchar(20), model nvarchar(20))

insert into Cars
select '123456', 2010, 'Ford', 'Focus'
union
select '123456', 2011, 'Ford', 'Focus'
union
select '654321', 2010, 'Opel', 'Astra'

返回

PartNumber    Year    Make    Model
654321        2010    Opel    Astra

答案 2 :(得分:0)

SELECT t.PartNumber, t.Yr, t.Make, t.Model, t2.yr
FROM cars t left outer join cars t2 on 
    t.PartNumber = t2.PartNumber
    AND t.Make = t2.Make
    AND t.Model = t2.Model
    and t.yr <> t2.yr 
WHERE t.Yr = 2011   AND (t2.yr <> 2012 or t2.Yr  is null)

应该处理

   part   make  model   yr 
   123456 Ford  Focus   2012 
   123456 Ford  Focus   2011 
   654321 Opel  Astra   2011 
   987654 Dodge Charger 2010 
   987654 Dodge Charger 2011

返回

part    yr      make    model   t2.yr
654321  2011    Opel    Astra   NULL
987654  2011    Dodge   Charger 2010