我需要按Property_externalID
和Lease_ExternalID
为每个分组的最小和最大日期列添加金额。
我将如何做到这一点?
示例:结果应该为每个分组返回一行:
Property_ExternalID Lease_ExternalID Min_Amount Max_Amount
------------------------------------------------------------------
27050 27050-0200 23 .02
表格样本数据:
Property_ExternalID Lease_ExternalID PropertyAssetId Date Amount
---------------------------------------------------------------------------
27050 27050-0200 6097 10/1/2017 23
27050 27050-0200 6097 4/1/2019 0.02
27050 27050-0200 6097 4/1/2021 0.02
27050 27050-0200 6097 4/1/2022 0.02
27050 27050-0200 6097 4/1/2023 0.02
27050 27050-0200 6097 4/1/2024 0.02
27050 27050-0200 6097 4/1/2025 0.02
27050 27050-0200 6097 4/1/2027 0.02
27050 27050-0200 6097 4/1/2026 0.02
答案 0 :(得分:1)
提供一些基本的SQL语句来创建表和数据总是有帮助的,这样帮助你的人可以尝试不同的东西。像这样......
IF OBJECT_ID('tempdb..#Temp', 'U') IS NOT NULL DROP TABLE #Temp;
CREATE TABLE #Temp
(
Property_ExternalID VARCHAR(15),
Lease_ExternalID VARCHAR(15),
PropertyAssetId VARCHAR(15),
Date DATE,
Amount DECIMAL(10, 2)
)
INSERT INTO #Temp VALUES ('27050', '27050-0200', '6097', '10/1/2017', 23)
INSERT INTO #Temp VALUES ('27050', '27050-0200', '6097', '04/1/2019', 0.02)
INSERT INTO #Temp VALUES ('27050', '27050-0200', '6097', '04/1/2021', 0.02)
INSERT INTO #Temp VALUES ('27050', '27050-0200', '6097', '04/1/2022', 0.02)
INSERT INTO #Temp VALUES ('27050', '27050-0200', '6097', '04/1/2023', 0.02)
INSERT INTO #Temp VALUES ('27050', '27050-0200', '6097', '04/1/2024', 0.02)
INSERT INTO #Temp VALUES ('27050', '27050-0200', '6097', '04/1/2025', 0.02)
INSERT INTO #Temp VALUES ('27050', '27050-0200', '6097', '04/1/2027', 0.02)
INSERT INTO #Temp VALUES ('27050', '27050-0200', '6097', '04/1/2026', 0.02)
鉴于此,您需要从主表连接到子查询,在子查询中您已确定每个Property_ExternalID
和Lease_ExternalID
的最小日期。然后你需要再次加入你的主表(因为Date的最小值和最大值可能会不同),然后再到另一个子查询,你已经确定每个{{1>的最大日期是什么}和Property_ExternalID
。
像这样......
Lease_ExternalID
诺尔
答案 1 :(得分:0)
您需要使用MIN和MAX aggregate functions以及GROUP BY子句。这对你有用......
DECLARE @MyDate AS DATE
-- comment the next line out if you want all dates
SET @MyDate = '04/01/2021'
SELECT Property_ExternalID, Lease_ExternalID, Date, MIN(Amount) AS 'Min_Amount',
MAX(Amount) AS 'Max_Amount'
FROM YourTable
WHERE Date = COALESCE(@MyDate, Date)
GROUP BY Property_ExternalID, Lease_ExternalID, Date
诺尔