如何防止仅针对列名过度使用 SELECT?
How to prevent over using SELECT just for column name?
如标题所示,有什么方法可以让我不必为列名调用那么多查询吗?
select val,
(select val1 FROM data WHERE size='a' AND cat ='1' ) as cat1_a,
(select val1 FROM data WHERE size='a' AND cat ='2' ) as cat2_a,
(select val1 FROM data WHERE size='b' AND cat ='1' ) as cat1_b,
(select val1 FROM data WHERE size='b' AND cat ='2' ) as cat2_b,
(select val1 FROM data WHERE size='c' AND cat ='1' ) as cat1_c,
(select val1 FROM data WHERE size='c' AND cat ='2' ) as cat2_c
from data
它并没有真正节省字符/输入,但您可以使用连接。
select t1.val, a1.val1 as cat1_a, a2.val1 as cat2_a
from data t1
left join data a1
on t1.val=a1.val
and a1.size = 'a'
and a1.cat = '1'
left join data a2
on t1.val=a2.val
and a2.size = 'a'
and a2.cat = '2'
我不知道你的数据是什么样的,但你可以尝试一些不同的结果
https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=a95ad5bd5c593c72354c24f9f867694a
如标题所示,有什么方法可以让我不必为列名调用那么多查询吗?
select val,
(select val1 FROM data WHERE size='a' AND cat ='1' ) as cat1_a,
(select val1 FROM data WHERE size='a' AND cat ='2' ) as cat2_a,
(select val1 FROM data WHERE size='b' AND cat ='1' ) as cat1_b,
(select val1 FROM data WHERE size='b' AND cat ='2' ) as cat2_b,
(select val1 FROM data WHERE size='c' AND cat ='1' ) as cat1_c,
(select val1 FROM data WHERE size='c' AND cat ='2' ) as cat2_c
from data
它并没有真正节省字符/输入,但您可以使用连接。
select t1.val, a1.val1 as cat1_a, a2.val1 as cat2_a
from data t1
left join data a1
on t1.val=a1.val
and a1.size = 'a'
and a1.cat = '1'
left join data a2
on t1.val=a2.val
and a2.size = 'a'
and a2.cat = '2'
我不知道你的数据是什么样的,但你可以尝试一些不同的结果 https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=a95ad5bd5c593c72354c24f9f867694a