我在Sql Server 2008中有两个表
Items
------
ItemNo
StartDate
Translation
-------
ItemNo
StartDate
Language
Description
在翻译表中,每种产品都有多种翻译,即。
ItemNo: 123
StartDate: 2011-11-02
Language: SE
Description: 'Bla1'
ItemNo: 123
StartDate: 2011-11-02
Language: DK
Description: 'Bla2'
如何构建快速选择语句,为每个产品输出单行而不使用太多查找,例如
Itemno StartDate DK SE
------------------------------------
123 2011-11-02 Bla1 Bla2
提前完成 延
答案 0 :(得分:2)
这是一个使用XML来完成你想要的版本。我没有根据评论部分中建议的其他方法测试性能。
除了它是StartDate
表中PK的一部分之外,看不出为什么Items
应该在两个表中。如果StartDate
不是PK的一部分,您可以安全地将其从所有联接中删除。
declare @Items table
(
ItemNo int,
StartDate date
)
declare @Translation table
(
ItemNo int,
StartDate date,
Language varchar(2),
Description varchar(20)
)
insert into @Items values
(123, '2011-11-02')
insert into @Translation values
(123, '2011-11-02', 'DK', 'Bla1'),
(123, '2011-11-02', 'SE', 'Bla2')
select I.ItemNo,
I.StartDate,
T.Trans.value('(Trans[@Language="DK"]/Desc)[1]', 'varchar(20)') as DK,
T.Trans.value('(Trans[@Language="SE"]/Desc)[1]', 'varchar(20)') as SE
from @Items as I
inner join (select T1.ItemNo,
T1.StartDate,
(select T2.Language as '@Language',
T2.Description as 'Desc'
from @Translation as T2
where T1.ItemNo = T2.ItemNo and
T1.StartDate = T2.StartDate
for xml path('Trans'), type) as Trans
from @Translation as T1
group by T1.ItemNo,
T1.StartDate) as T
on I.ItemNo = T.ItemNo and
I.StartDate = T.StartDate