SQL查询来自一列的最小值(日期)和来自另一列的最大值(金额)

时间:2016-08-08 20:15:17

标签: sql-server date aggregate-functions sqldatetime

我有一张桌子,看起来像是

Table I have

我需要创建一个由以下列组成的表

Table I need

表格包括唯一ID,短信数量最大时的最小日期和短信数量最小时的最大日期,包括两种情况下的短信数量

我已经尝试了几个查询,但我觉得问题不在于在“sms”列中找到min(sms),而是在“date”列中使用条件max(date)

因此,如果我必须找到最小数据发送的最大数量的短信,我应该在数字最大时选择最小数据。现在我只能找到最小数据发送的短信数量。

对任何解释都很高兴

P.S。:我正在使用MS SQL 2014

1 个答案:

答案 0 :(得分:0)

这应该起作用或者至少是起点:

SELECT * INTO Table1 FROM (VALUES
(1,'1/1/2015',10),
(1,'2/1/2015',10),
(1,'3/1/2015',20),
(1,'4/1/2015',20),
(2,'5/1/2015',30),
(2,'6/1/2015',30),
(2,'7/1/2015',40),
(2,'8/1/2015',40)
) as x ([User_ID], [Date], [SMS])
GO
;WITH MX as (
    SELECT t1.[User_ID], MIN(t1.[Date]) as [Date], t1.[SMS]
    FROM Table1 as t1
    WHERE t1.[SMS] = (SELECT MAX(i.[SMS]) as [SMS] FROM Table1 as i WHERE i.[User_ID] = t1.[User_ID] ) 
    GROUP BY t1.[User_ID], t1.[SMS]
), MI as (
    SELECT t1.[User_ID], MAX(t1.[Date]) as [Date], t1.[SMS]
    FROM Table1 as t1
    WHERE t1.[SMS] = (SELECT MIN(i.[SMS]) as [SMS] FROM Table1 as i WHERE i.[User_ID] = t1.[User_ID] ) 
    GROUP BY t1.[User_ID], t1.[SMS]
)
SELECT MX.[User_ID], MX.[Date] as Min_Date, MX.[SMS] as Max_SMS, MI.[Date] as Max_Date, MI.[SMS] as Min_SMS
FROM MX INNER JOIN MI ON MX.[User_ID] = MI.[User_ID];
GO