![](/img/trans.png)
[英]Is there a better way to write this Oracle SQL that deals with comparing dates in two different columns?
[英]It is required to write a query that returns, for two dates, the total balances of active deals on these dates in SQL
給出下表:
列
這里有張桌子:
開始日期 | 結束日期 | 數量 |
---|---|---|
01.01.2020 | 01.01.2021 | 1個 |
15.04.2020 | 15.04.2021 | 3個 |
需要編寫一個查詢,返回兩個日期的活躍交易在這些日期的總余額。
需要在日期 1 = 02.05.2020 和日期 2 = 02.02.2021 顯示余額
我知道如何一一得到它們
SELECT SUM(Amount)
FROM Table
WHERE 02.05.2020 >= End Date
要么
SELECT SUM(Amount)
FROM Table
WHERE 02.05.2020 >= End Date OR 02.02.2021 >= End Date
但我不知道如何為日期創建一個單獨的表:
date 1 || amount 1
date 2 || amount 2
你能給我一些解決方案的建議或指導嗎?
您可以使用條件聚合或過濾總和 function,如下所示:
SELECT
SUM(CASE WHEN '02.05.2020' >= End_Date THEN Amount ELSE 0 END) AS Date1,
SUM(CASE WHEN '02.05.2020' >= End_Date OR '02.02.2021' >= End_Date THEN Amount ELSE 0 END) AS Date2
FROM table_name
要么:
SELECT
SUM(Amount) FILTER (WHERE '02.05.2020' >= End_Date) AS Date1,
SUM(Amount) FILTER (WHERE '02.05.2020' >= End_Date OR '02.02.2021' >= End_Date) AS Date2
FROM table_name
看一個演示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.