简体   繁体   中英

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.

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.

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.

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). I show you here a link with the theory:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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