SQL选择具有最大值的所有ID,然后计算与每个id关联的行数

时间:2016-11-12 04:25:20

标签: sql db2

假设我有下表 HASCO

Table HASCO

+--------+------+-----+
|PID     |Amount|Date |
+--------+------+-----+
|1       |1000  |Date1|
+--------+------+-----+
|1       |8000  |Date2|
+--------+------+-----+
|2       |8000  |Date3|
+--------+------+-----+
|2       |3000  |Date4|
+--------+------+-----+
|2       |4000  |Date5|
+--------+------+-----+
|3       |4000  |Date6|
+--------+------+-----+

我想得到以下结果:

+--------+--------+
|PID     |numTours|
+--------+--------+
|1       |2       |
+--------+--------+
|2       |3       |
+--------+--------+

PID 1和2的最大值均为8000,则PID 1为2行,PID 2为3行。

我尝试了以下查询:

SELECT HASCO.PID, COUNT(*) AS numTour
FROM HASCO
GROUP BY HASCO.PID
HAVING HASCO.PID IN
(
SELECT HASCO.PID
FROM HASCO
WHERE HASCO.AMOUNT = (SELECT MAX(HASCO.AMOUNT) FROM HASCO)

这适用于db2但是有更好的方法吗?

4 个答案:

答案 0 :(得分:3)

Having子句中的子查询可以简化为

SELECT HASCO.PID, COUNT(*) AS numTour
FROM HASCO
GROUP BY HASCO.PID
HAVING max(HASCO.AMOUNT) = (SELECT MAX(HASCO.AMOUNT) FROM HASCO)

如果DB2支持窗口聚合函数,那么

Select PID,count(1)
(
Select HASCO.PID,
       Max(AMOUNT)Over() as Max_amount,
       Max(AMOUNT) Over(Partition by PID) as Max_Pid_Amt
From HASCO
) A
Where Max_amount = Max_Pid_Amt
Group by PID

答案 1 :(得分:0)

解决方案1 ​​

WITH MAXIVALUE(SELECT MAX(HASCO.AMOUNT) maxi FROM HASCO)
SELECT f1.PID, COUNT(*) AS numTours
FROM HASCO f1
GROUP BY f1.PID
HAVING max(f1.AMOUNT) = (SELECT maxi  FROM MAXIVALUE)

答案 2 :(得分:0)

解决方案2

with hasmaxi (
select distinct f1.pid from HASCO f1
where exists 
(select 1 from HASCO f2 having max(f2.AMOUNT)=f1.AMOUNT)
)
SELECT f3.PID, COUNT(*) AS numTours
FROM HASCO f3 inner join hasmaxi f4 on f3.PID=f4.f1.PID
GROUP BY f3.PID

答案 3 :(得分:0)

解决方案3

SELECT f3.PID, COUNT(*) AS numTours
FROM HASCO f3 inner join 
               (
                 select distinct f1.pid from HASCO f1
                 where exists 
                 (select 1 from HASCO f2 having max(f2.AMOUNT)=f1.AMOUNT)
               ) f4 on f3.PID=f4.f1.PID
GROUP BY f3.PID