![](/img/trans.png)
[英]SQL Select rows with column values that match column values in different table
[英]SQL select rows with different values in two column
我有 4-5 个表的数据库。 我正在收集这样的数据
N | Nom_ | Soni_ | Savdo | Foyda | Val(Currency) 1 | Apple | 5kg | 5000 | 500 | UZS 2 | Banana| 4kg | 7000 | 800 | UZS 3 | Peach | 2kg | 2 | 0.2 | USD
我想将货币列分开两列,如下所示
N | Nom_ | Soni_ | Savdo | Foyda | Val1 | Val2 1 | Apple | 5kg | 5000 | 500 | UZS | 2 | Banana| 4kg | 7000 | 800 | UZS | 3 | Peach | 2kg | 2 | 0.2 | | USD
这是我的 SQL 代码。
select s.nom_ , sum(o.soni_) as soni_ ,
sum(o.soni_*(select narx_ from toper where id_=o.id_ )) as savdo_,
sum((o.soni_*o.narx_-o.soni_* (select narx_ from toper where id_=o.id_op ))) as foyda_,
(select nom_ from tsinf where id_=o.id_v) as val_
from toper o left join tsf f on o.id_sf=f.id_
left join tsinf s on o.id_s=s.id_
where (f.date_>=date('2020-01-01')) and (f.date_<=date('2020-04-04'))
and f.oper_=-1 group by id_s, id_v
将您的查询放在CTE
,然后使用CASE
表达式选择 2 列:
with cte as (
select s.nom_ , sum(o.soni_) as soni_ ,
sum(o.soni_*(select narx_ from toper where id_=o.id_ )) as savdo_,
sum((o.soni_*o.narx_-o.soni_* (select narx_ from toper where id_=o.id_op ))) as foyda_,
(select nom_ from tsinf where id_=o.id_v) as val_
from toper o left join tsf f on o.id_sf=f.id_
left join tsinf s on o.id_s=s.id_
where (f.date_>=date('2020-01-01')) and (f.date_<=date('2020-04-04'))
and f.oper_=-1
group by id_s, id_v
)
select nom_, soni, savdo, foyda_,
case when val_ = 'UZS' then val_ end as Val1,
case when val_ = 'USD' then val_ end as Val2
from cte
但是你应该知道条件:
where (f.date_>=date('2020-01-01')) and (f.date_<=date('2020-04-04'))
将您的left
连接更改为tsf
到inner
连接。 如果结果是你所期望的,那很好。 如果不将这些条件移动到ON
子句。
此外,如果关系是 1:1,您可以使用joins
而不是您在选择列表中使用的所有select
语句。
尝试这个:
select
s.nom_,
sum(o.soni_) as soni_,
sum(o.soni_* o2.narx_) as savdo_,
sum((o.soni_*o.narx_-o.soni_* o3.narx_) as foyda_,
case when s2.nom_ = 'UZS' then s2.nom_ end as Val1,
case when s2.nom_ = 'USD' then s2.nom_ end as Val2
from toper o
left join toper o2 on o2.id_=o.id_
left join toper o3 on o3.id_=o.id_op
left join tsf f on o.id_sf=f.id_
left join tsinf s on o.id_s=s.id_
left join tsinf s2 on o.id_v=s2.id_
where (f.date_>=date('2020-01-01')) and (f.date_<=date('2020-04-04')) and f.oper_=-1
group by id_s, id_v
我会将子查询移动到FROM
子句(使用LEFT JOIN
)。 那么拆分只是两个CASE
表达式:
select s.nom_ , sum(o.soni_) as soni_,
sum(o.soni_*(select narx_ from toper where id_=o.id_ )) as savdo_,
sum((o.soni_*o.narx_-o.soni_* (select narx_ from toper where id_=o.id_op ))) as foyda_,
(case when sv.nom_1 = 'UZS' then sv.nom_1 end) as uzs,
(case when sv.nom_1 = 'USD' then sv.nom_1 end) as usd
from toper o left join
tsf f
on o.id_sf = f.id_ left join
tsinf s
on o.id_s = s.id_ left join
tsinf sv
on sv.id_ = o.id_v
where f.date_ >= date('2020-01-01') and
f.date_ <= date('2020-04-04') and
f.oper_ = -1
group by id_s, id_v ;
我还建议删除toper
的子查询,但这将是另一个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.