繁体   English   中英

动态 SQL 透视

[英]Dynamic SQL pivoting

我有一个表贷款结构如下:

Ccy  | interest1| interest2
GBP  |   75     |      95
USD  |   30     |      50

我有以下任务:

我希望我的输出只有当利息 1 + 利息 2 大于 200 时才有英镑,只有当利息 1 + 利息 2 大于 50 时,我的输出才应该有美元。

输出应如下所示,请参阅输出中没有英镑,因为利息总和仅为 170,低于 200,并且由于美元在输出中大于 50。

USD
80

我使用了下面的查询。 但是,它也显示英镑。 我不想看到英镑。 它必须显示唯一的美元。 因为,英镑不超过200。

with a as (select ccy,(interest1 + interest2) as amount from my_table where 
(case when (ccy = 'GBP' and (interest1+interest2) > 200) then 1
      when (ccy = 'USD' and (interest1+interest2) > 50) then 1 end) = 1 )
Select * from a 
      pivot (sum(amount) for ccy in ('GBP' as GBP, 'USD' as USD))
Select Ccy, interest1, interest2
from table
where (Ccy = "GBP" and (interest1 + interest2) > 200) or (Ccy = "USD" and (interest1 + interest2) > 50)

我不确定您是否希望两个数字一起更大,那么特定值或两个数字一起必须更大。 这是解决方案,当一行的两个数字都更大时。

好吧,你想做这个任务(我想)从另一个地方(网络,服务......)给她打电话,然后我建议你从贷款表中创建一个视图,然后在这个视图中你可以指定如何工作(如果Interest1 + Interest2 > 200 然后以英镑和所有你想要的形式输出)。 我在这里向您展示与该理论的链接:

https://www.w3schools.com/sql/sql_view.asp

然后在知道之后,你必须做这样的事情:

-- SQL Code in 1 query: CREATE VIEW [Suitables_Prices] AS SELECT Ccy, interest1 + interest2 AS interest FROM LoanTable WHERE (Ccy = 'GBP' and (interest1 + interest2) > 200) or (Ccy = 'USD' and (interest1 + interest2) <= 200 and (interest1 + interest2) >= 50);

这分别输出名称和感兴趣的总和。 通过这种方式,您正在以感兴趣的价值为中心……

或者你可以使用数据库中的过程来做同样的事情,但我认为视图更容易更好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM