0

我正在使用 SQL Server 2008 R2。我在表格中有如下记录:

Id  Sys   Dia   Type        UniqueId
1   156   20    first       12345
2   157   20    first       12345
3   150   15    last        12345
4   160   17    Average     12345
5   150   15    additional  12345
6   157   35    last        891011
7   156   25    Average     891011
8   163   35    last        789521
9   145   25    Average     789521
10  156   20    first       963215
11  150   15    last        963215
12  160   17    Average     963215
13  156   20    first       456878
14  157   20    first       456878
15  150   15    last        456878
16  160   17    Average     456878
17  150   15    last        246977
18  160   17    Average     246977
19  150   15    additional  246977

关于这些数据,这些记录是具有共同 UniqueId 的组。记录的类型可以是“第一个、最后一个、平均和附加”。现在,我想从这些记录中选择“平均”类型的记录,前提是它们在组中有“第一次”或“附加”类型的阅读。否则我想将它们排除在选择之外..

预期结果是:

Id  Sys   Dia   Type        UniqueId
1   156   20    first       12345
2   157   20    first       12345
3   150   15    last        12345
4   160   17    Average     12345
5   150   15    additional  12345
6   157   35    last        891011
7   163   35    last        789521
8   156   20    first       963215
9   150   15    last        963215
10  160   17    Average     963215
11  156   20    first       456878
12  157   20    first       456878
13  150   15    last        456878
14  160   17    Average     456878
15  150   15    last        246977
16  160   17    Average     246977
17  150   15    additional  246977

简而言之,我不想选择具有 type="Average" 并且只有具有相同 UniqueId 的“最后”类型的记录的记录。有什么解决办法吗?

4

2 回答 2

2

尝试这样的事情:

SELECT * FROM MyTable WHERE [Type] <> 'Average'
UNION ALL
SELECT * FROM MyTable T WHERE [Type] = 'Average'
    AND EXISTS (SELECT * FROM MyTable 
                WHERE [Type] IN ('first', 'additional') 
                    AND UniqueId = T.UniqueId)

第一个 SELECT 语句获取除 Type = 'Average' 之外的所有记录。第二个 SELECT 语句仅获取 Type = 'Average' 记录,这些记录至少有一个具有相同 UniqueId 的记录,即类型为“first”或“additional”。

于 2013-10-07T12:28:25.430 回答
2

EXISTS沿相关子查询使用运算符:

SELECT * FROM dbo.Table1 t1
WHERE [Type] != 'Average' 
OR EXISTS (SELECT * FROM Table1 t2 
           WHERE t1.UniqueId = t2.UniqueId 
             AND t1.[Type] = 'Average' 
             AND t2.[Type] IN ('first','additional'))

SQLFiddle 演示

于 2013-10-07T12:33:49.743 回答