max,min进入一个T-SQL查询

时间:2014-09-03 18:40:13

标签: sql max min

我有桌子:

create table dbo.call (
subscriber_name varchar(64)     not null
,   event_date      datetime    not null
,   event_cnt       int     not null
)

需要编写一个查询,为每个订阅者返回事件数量最少的日期,事件数量最小的最大日期以及事件数量。

结果:

subscriber_name |   min_date    |   max_event_cnt | max_date    |    min_event_cnt
----------------------------------------------------------------------------------
Subscriber1     |   20091012    |   15  20061012  | 10          |
----------------------------------------------------------------------------------
Subscriber2     |   20080301    |   20  20090513  | 8           |
----------------------------------------------------------------------------------

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

SELECT
  t1.subscriber_name,
  min_date,
  max_event_cnt,
  max_date,
  min_event_cnt
FROM
(
  SELECT 
    subscriber_name, 
    MIN(event_date) AS min_date,
    MAX(event_cnt) AS max_event_cnt
  FROM
    dbo.call
  GROUP BY
    subcriber_name
  ) t1
JOIN
(
  SELECT 
    subscriber_name, 
    MAX(event_date) AS max_date,
    MIN(event_cnt) AS min_event_cnt
  FROM
    dbo.call
  GROUP BY
    subcriber_name
  ) t2
ON t1.subscriber_name = t2.subscriber_name