从SQL选择中返回最大值

时间:2015-05-25 18:32:09

标签: sql sql-server sql-server-2012

我确实有一个表license_Usage,其工作方式就像一天中许可证使用情况的记录一样

ID   User        license    date
1    1            A      22/2/2015
2    1            A      23/2/2015
3    1            B      22/2/2015
4    2            A      22/2/2015

我希望计算一天中每位用户的许可数量,结果应如下:

QuantityOfLicenses         User      date
        2                   1      22/2/2015
        1                   2      22/2/2015

为此,我做了以下查询:

select count(license) as [Quantity of licenses],[user],[date]
From license_Usage
where date = '22/2/2015'
Group by [date], [user]

有效,但知道我想知道哪个用户使用了最多的许可证,因为我做了以下查询:

select MAX(result.[Quantity of licenses])
From (
     select count(license) as [Quantity of licenses],[user],[date]
     From license_Usage
     Group by [date], [user]
    ) as result

它返回最大值2,但是当我想知道哪个用户使用了2个许可证时,我尝试此查询但没有成功:

select result.user, MAX(result.[Quantity of licenses])
From (
     select count(license) as [Quantity of licenses],[user],[date]
     From license_Usage
     Group by [date], [user]
    ) as result
Group by result.user

3 个答案:

答案 0 :(得分:2)

您可以使用以下内容:

select top 1 *
From (
     select count(license) as Quantity,[user],[date]
     From license_Usage
     Group by [date], [user]
    ) as result
order by Quantity desc

如果您需要获取一个获取具有最大值的所有行的提取,以防有几个,那么您必须使用rank()窗口函数

答案 1 :(得分:0)

使用RANK按用户每天的许可数量对用户进行排名。

SELECT
  LicPerDay.*,
  RANK() OVER (PARTITION BY [date] ORDER BY Qty DESC) AS User_Rank
FROM (
  SELECT
    COUNT(license) AS Qty,
    User,
    [date]
  FROM license_usage
  GROUP BY User, [date]
) LicPerDay

User_Rank = 1的任何用户拥有当天最多的许可。

如果您只想要每天的顶级用户,请将上面的查询包装为子查询并过滤User_Rank = 1

SELECT * FROM (
  SELECT
    LicPerDay.*,
    RANK() OVER (PARTITION BY [date] ORDER BY Qty) AS User_Rank
  FROM (
    SELECT
      COUNT(license) AS Qty,
      User,
      [date]
    FROM license_usage
    GROUP BY User, [date]
  ) LicPerDay
) LicPerDayRanks
WHERE User_Rank = 1

答案 2 :(得分:0)

使用窗口聚合函数RANK获得最高计数:

SELECT * FROM (
    SELECT
      User,
      [date]
      COUNT(license) AS Qty,
      -- rank by descending number for each day ??
      --RANK() OVER (PARTITION BY [date] ORDER BY COUNT(license) DESC) AS rnk
      -- rank by descending number
      RANK() OVER (ORDER BY COUNT(license) DESC) AS rnk
    FROM license_usage
    GROUP BY User, [date]
  ) dt
WHERE rnk = 1