查找另一个Max查询的最大值

时间:2014-11-24 07:18:11

标签: sql max

我有一个数据表,如下所示:

+--------+----------+------------+
| Client | Item No. | Serial No. |
+--------+----------+------------+
| A      |        1 |          1 |
| A      |        1 |          2 |
| B      |        1 |          2 |
| B      |        2 |          1 |
| C      |        2 |          3 |
| C      |        2 |          2 |
| C      |        3 |          1 |
| C      |        3 |          2 |
| D      |        2 |          3 |
| D      |        2 |          1 |
| D      |        3 |          2 |
| D      |        3 |          3 |
| D      |        2 |          2 |
| D      |        3 |          1 |
+--------+----------+------------+

我要做的是为每个客户找到最高项目编号,然后是最高序列号(按此顺序)。所以对于上面的输出将是:

+--------+----------+------------+
| Client | Item No. | Serial No. |
+--------+----------+------------+
| A      |        1 |          2 |
| B      |        2 |          1 |
| C      |        3 |          2 |
| D      |        3 |          3 |
+--------+----------+------------+

我认为这需要一个嵌套的MAX()语句,首先为每个客户端获取 MAX(项目编号),对于那些具有多个客户端的人,然后获取 MAX(序列号)编写此查询的有效方法是什么?

3 个答案:

答案 0 :(得分:1)

也许这会有所帮助:

SELECT t.client,
       t.item,
       MAX(t.serial) AS serial
  FROM(SELECT client,
              MAX(item) AS item
         FROM your_table
        GROUP
           BY client
      ) a
  JOIN your_table t
    ON a.client = t.client AND a.item = t.item
 GROUP
    BY t.client, t.item 

如果你的DBMS支持窗口函数,另一种方法是:

SELECT client, item, serial
  FROM(SELECT client, item, serial,
              ROW_NUMBER() OVER (PARTITION BY client ORDER BY item DESC, serial DESC) rn
         FROM your_table
      )
 WHERE rn = 1

答案 1 :(得分:0)

Postgres有一个很棒的捷径

SELECT DISTINCT ON (Client) Client, Item, SerialNumber
FROM some_table
ORDER BY Item DESC, SerialNumber DESC -- DESC gets highest

由于DISTINCT,每个客户端只能获取一条记录,而ORDER BY会确保它是您想要的记录。

我不知道是否有任何其他DBMS会如此轻易地做到这一点。

答案 2 :(得分:0)

这是解决方案:

WITH CTE AS (
SELECT Client, MAX(Item_No) AS  Item_No
FROM YourTable 
GROUP BY Client)

SELECT a.Client,b.Item_No,MAX(Serial_No) AS Serial_No 
FROM CTE a
JOIN YourTable b ON a.Client = b.Client AND a.Item_No = b.Item_No
GROUP BY a.Client,b.Item_No