我的表格中有type
列,type
列值为HOT
和NOT
。从那里我希望将列的HOT
和NOT
值显示为一行。
实施例
表1
Period ID Total
11/2011 101 250
12/2011 102 350
11/2011 103 450
....
表2
Period ID Type Value
11/2011 101 NOT 500
11/2011 101 HOT 200
12/2011 102 NOT 300
12/2011 102 HOT 200
....
我想将类型(Hot
和Not
)显示在一行
预期产出
Period ID NOT HOT Total
11/2011 101 500 200 250
12/2011 102 300 200 350
11/2011 103 300 400 450
....
如何进行查询。
答案 0 :(得分:3)
如果我可以假设table1的主键为(Period,ID)且table2的主键为(Period,ID,Type),那么你可以这样做:
select
t1.period
, t1.id
, t2n.value [not]
, t2h.value [hot]
, t1.total
from
table1 t1
left join table2 t2n
on t1.period = t2n.period
and t1.id = t2n.id
and t2n.type = 'Not'
left join table2 t2h
on t1.period = t2h.period
and t1.id = t2h.id
and t2h.type = 'Hot'
这将检索表1中的所有行,其对应的“非”和“热”对应,分别对应于上面的t2n和t2h。
答案 1 :(得分:2)
你试过这个吗?
select base.period, base.id, sum( notchild.value ) as notsum, sum( hotchild.value ) as hotsum, base.total
from table1 base
left outer join table2 notchild
on base.period = notchild.period and base.id = notchild.id and notchild.type = 'NOT'
left outer join table2 hotchild
on base.period = hotchild.period and base.id = hotchild.id and hotchild.type = 'HOT'
group by base.period, base.id, base.total
答案 2 :(得分:0)
您可以使用JOIN
(检查this)来执行此操作。加入你的两个表并在其上执行SELECT
。