2

我无法找出查询。我有 3 张桌子。我想出了如何从表格中获取数据以显示在一行中,但是其中一张表格的数据设置很奇怪。所有表共享一个报告 ID。

表格1

RID AllOtherData
1    Stuff
2    Stuff
3    Stuff

表 2

RID Description
1   Descript
2   Descript
3   Descript

表3是我遇到麻烦的地方

RID Item Code
1     1   RWA
1     2   ABA
1     3   BBC
2     1   BBC
2     2   NULL
2     3   NUll
ETC*

我要问的是如何查询以获取RID, ALLotherstuf.T1, descript.t2, code.t3 as item1 code, code.t3 as item2 code, code.t3 as item3代码。

如果有人能指出我或给我一个例子说明这是什么类型的查询,甚至可能我会非常感激。

4

3 回答 3

1

这是你要找的吗?这是从@Gordon 之前的回复中修改的。

select t1.RID, t1.AllOtherData, t2.Description,
       max(case when t3.item = 1 then t3.code end) as item1code,
       max(case when t3.item = 2 then t3.code end) as item2code,
       max(case when t3.item = 3 then t3.code end) as item3code
from table1 t1 join
     table2 t2 on 
     t1.RID = t2.RID join
     table3 t3 on
     t1.RID = t3.RID
group by t1.RID, t1.AllOtherData, t2.Description

还有SQL 小提琴

于 2013-01-10T16:41:47.503 回答
0

您想要旋转列。首先,将所有表连接在一起。这会在单独的行上生成代码。要将它们放在一排,请使用group by. 以下适用于任何数据库:

select t1.RID, t1.ALLotherstuf, t2.descript,
       max(case when t3.item = 1 then t3.code end) as item1code,
       max(case when t3.item = 2 then t3.code end) as item2code,
       max(case when t3.item = 3 then t3.code end) as item3code
      code.t3 as item1 code, code.t3 as item2 code, code.t3 as item3
from t1 join
     t2 o
     on t1.RID = t2.RID join
     t3
     on t1.RID = t3.RID
group by t1.RID, t1.ALLotherstuf, t2.descript
于 2013-01-10T16:32:24.380 回答
0

如果您使用的是 SQL Server,您还可以使用以下PIVOT功能:

select *
from
(
  select t1.RID, 
    t1.AllOtherData, 
    t2.Description,
    t3.item,
    t3.code
  from table1 t1 
  inner join table2 t2 
    on t1.RID = t2.RID 
  inner join table3 t3 
    on t1.RID = t3.RID
) src
pivot
(
  max(code)
  for item in ([1], [2], [3])
) piv

请参阅带有演示的 SQL Fiddle

于 2013-01-10T17:17:53.507 回答