选择最大记录

时间:2018-12-31 23:09:03

标签: sql oracle oracle10g

我希望查询仅在每个图表ID的最大图表版本为图表类型Q时返回图表点的计数。我希望它仅在图表类型Q时才计数。

(CHART_ID,CHART_TYPE,CHART_VERSION,CNT)
(CHART1,Q,11,10)
(CHART1,Q,13,20)
(CHART1,I,14,5)

SELECT
    CHART_ID,
    CHART_TYPE,
    CHART_VERSION,
    COUNT(CHART_POINTS) AS CNT
FROM CHART_TABLE
WHERE
    CHART_TYPE = 'Q' AND 
    CHART_ID = 'CHART1'
GROUP BY
    CHART_ID,
    CHART_TYPE,
    CHART_VERSION
ORDER BY
    CHART_ID ASC

查看查询

此图表ID应该返回(CHART1,Q,13,20)。

1 个答案:

答案 0 :(得分:1)

这个有效:

WITH cte AS (
    SELECT
        CHART_ID,
        CHART_TYPE,
        CHART_VERSION,
        COUNT(CASE WHEN CHART_TYPE = 'Q' THEN 1 END) OVER
            (PARTITION BY CHART_ID, CHART_VERSION) CNT,
        ROW_NUMBER() OVER (PARTITION BY CHART_ID ORDER BY CHART_VERSION DESC) rn
    FROM CHART_TABLE
)

SELECT
    CHART_ID,
    CHART_TYPE,
    CHART_VERSION,
    CNT
FROM cte
WHERE
    rn = 1 AND CHART_TYPE = 'Q'