簡體   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