Sql 如何显示两行中的一行
我的表中有Sql 如何显示两行中的一行,sql,sql-server,sql-server-2000,Sql,Sql Server,Sql Server 2000,我的表中有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 .... 我想在一行中显示类型(H
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
....
如何进行查询。您尝试过这个吗
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
你试过这个吗
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
您可以使用
JOIN
(检查)来执行此操作。连接两个表并在其上执行选择。您可以使用连接
(检查)来执行此操作。连接两个表并对其执行选择。如果我可以假设表1的主键为(句点,ID),表2的主键为(句点,ID,类型),那么您可以执行以下操作:
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中的所有行及其对应的“not”和“hot”对应项,分别对应于上面的t2n和t2h。如果我可以假设表1的主键为(Period,ID),而表2的主键为(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中的所有行,以及它们对应的“not”和“hot”对应项,分别对应于上面的t2n和t2h。您可能忘记添加notchild.type='not'
和hotchild.type='hot'
。您完全正确!很抱歉看到了原来的海报。我会立即修改答案。您可能忘记在某个地方添加notchild.type='NOT'
和hotchild.type='HOT'
(很可能是加入条件)。您完全正确!很抱歉看到了原来的海报。我马上修改答案。也有可能(ID)
是表1
的主键和(ID,Type)
表2
,和表2.Period
是一个重复表1的冗余列。Period
@CD Jorgensen,它在工作,但在表2中,我的Period比表1多,所以我想显示表2和表2中的所有其他时间段table1@RemoRose:尝试完全联接而不是左联接;要获取期间
和id
的正确结果,请使用大小写
表达式或合并()。也有可能(ID)
是表1
的主键和(ID,Type)
表2
,和表2.Period
是一个重复表1的冗余列。Period
@CD Jorgensen,它在工作,但在表2中,我的Period比表1多,所以我想显示表2和表2中的所有其他时间段table1@RemoRose:尝试完全联接而不是左联接;要获取期间
和id
的正确结果,请使用大小写
表达式或合并()。