一个棘手的查询 - 有点不同

时间:2016-06-30 08:40:58

标签: sql sql-server

我有一个包含翻译的表格(示例已简化):

具有GroupId = 0的那些是全局的,具有GroupId>的那些是全局的。 0是特定于该组。

ID(BitInt), TranslationId(BigInt), GroupId(BigInt), Translation(VarChar(100)
1           1                      0               'Hello'
2           1                      20              'Hi there'
3           1                      25              'Hi'
4           2                      0               'Goodbye'
5           3                      20              'See you'
6           3                      25              'See Ya'
7           4                      25              'Well well'

我需要从中选择一个特定的小组给我:

如果存在具有正确GroupId的记录,则该记录存在具有GroupId = 0的全局记录

所以我想说我用GroupId = 20进行查询 它应该返回

2,1,20,'Hi there'
4,2,0,'Goodbye'
5,3,20,'See you'

GroupId = 25的查询

3,1,25,'Hi'
4,2,0,'Goodbye'
6,3,25,'See Ya'
7,4,25,'Well well'

GroupId = 37的查询

1,1,0,'Hello'
4,2,0,'Goodbye'

希望这能提供某种意义,并提前感谢:)

1 个答案:

答案 0 :(得分:0)

以下是一种方法(假设TranslationIdGroupId的组合是唯一的):

创建并填充样本表(在下一个问题中将此步骤保存起来)

DECLARE @T As TABLE 
(
    ID BigInt, 
    TranslationId BigInt, 
    GroupId BigInt, 
    Translation VarChar(100)
)

INSERT INTO @T VALUES
(1, 1, 0, 'Hello'),
(2, 1, 20, 'Hi there'),
(3, 1, 25, 'Hi'),
(4, 2, 0, 'Goodbye'),
(5, 3, 20, 'See you'),
(6, 3, 25, 'See Ya'),
(7, 4, 25, 'Well well')

查询:

DECLARE @GroupId BigInt = 20

SELECT ID, TranslationId, GroupId, Translation
FROM @T 
WHERE GroupId = @GroupId

UNION ALL

SELECT T1.ID, T1.TranslationId, T1.GroupId, T1.Translation
FROM @T T1
LEFT JOIN @T T2 ON(T1.TranslationId = T2.TranslationId AND T2.GroupId = @GroupId)
WHERE T1.GroupId = 0
AND T2.Id IS NULL

结果:

@GroupId = 20

ID                   TranslationId        GroupId              Translation
-------------------- -------------------- -------------------- -----------
2                    1                    20                   Hi there
5                    3                    20                   See you
4                    2                    0                    Goodbye

@GroupId = 25

ID                   TranslationId        GroupId              Translation
-------------------- -------------------- -------------------- -----------
3                    1                    25                   Hi
6                    3                    25                   See Ya
7                    4                    25                   Well well
4                    2                    0                    Goodbye

@GroupId = 37 (样本数据中不存在)

ID                   TranslationId        GroupId              Translation
-------------------- -------------------- -------------------- -----------
1                    1                    0                    Hello
4                    2                    0                    Goodbye