简体   繁体   English

动态 SQL 透视

[英]Dynamic SQL pivoting

I have a table loan with the structure as below:我有一个表贷款结构如下:

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

I have the task below:我有以下任务:

I want my output to have GBP only when interest1 + interest 2 is greater than 200 and my output should have USD only when interest 1 + interest 2 is greater than 50.我希望我的输出只有当利息 1 + 利息 2 大于 200 时才有英镑,只有当利息 1 + 利息 2 大于 50 时,我的输出才应该有美元。

The output should be as below, see GBP is not there in output as sum of interest is only 170 which is below 200 and since USD is greater than 50 it in the output.输出应如下所示,请参阅输出中没有英镑,因为利息总和仅为 170,低于 200,并且由于美元在输出中大于 50。

USD
80

I used the query below.我使用了下面的查询。 But, it shows GBP, too.但是,它也显示英镑。 I don't want GBP to be seen.我不想看到英镑。 It must show the only USD.它必须显示唯一的美元。 Because, the GBP is not over 200.因为,英镑不超过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)

I am not sure if you want both numbers together to be bigger then the specific values or both numbers together has to be bigger.我不确定您是否希望两个数字一起更大,那么特定值或两个数字一起必须更大。 This is the solution, when both numbers for a row together are bigger.这是解决方案,当一行的两个数字都更大时。

Well, you wanna do this task (I suppose) to call her from another place (web, service..), then I recommend you that you make a View from the loan table, then in this view you can specify how works (if interest1 + interest2 > 200 then outputs in GBP and all that you want).好吧,你想做这个任务(我想)从另一个地方(网络,服务......)给她打电话,然后我建议你从贷款表中创建一个视图,然后在这个视图中你可以指定如何工作(如果Interest1 + Interest2 > 200 然后以英镑和所有你想要的形式输出)。 I show you here a link with the theory:我在这里向您展示与该理论的链接:

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

Then after know that, you must do something like this:然后在知道之后,你必须做这样的事情:

-- 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);

This outputs the name and the sum of interest respectively.这分别输出名称和感兴趣的总和。 In this way you are pivoting with the value of interest...通过这种方式,您正在以感兴趣的价值为中心……

Or you can do the same using procedures from database, but I think a view is easier and better.或者你可以使用数据库中的过程来做同样的事情,但我认为视图更容易更好。

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

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