如何在oracle中获取pivot行的摘要

时间:2016-03-16 14:58:02

标签: sql database oracle pivot oracle-sqldeveloper

我有一个查询:

WITH dane AS (
SELECT PACJENT.PLEC, JOS.NAZWA
FROM PACJENT
INNER JOIN POBYT ON PACJENT.ID_PAC = POBYT.ID_PAC
INNER JOIN JOS ON JOS.IDK_JOS = POBYT.IDK_JOS
WHERE trunc(months_between(POBYT.DT_OD,PACJENT.DATA_UR)/12)> 65)
SELECT NAZWA,K,M ,K+M as suma FROM dane
PIVOT (
COUNT(*)
FOR PLEC
IN ('M' as K,'K' as M)
)

输出如:

Radioterapia        2056    1775    3831
Poradnia WZW        689     909     1598
Ambulatorium ogólne 705     1150    1855

但是我需要所有列的总行数:

    Radioterapia        2056    1775    3831
    Poradnia WZW        689     909     1598
    Ambulatorium ogólne 705     1150    1855
    ---
    TOTAL               3450    3834    7284

我该怎么做?谢谢你的进步。

1 个答案:

答案 0 :(得分:0)

假设您需要使用SQL查询提取总行,您可以尝试使用以下内容包装查询:

    WITH dane AS
         (SELECT PACJENT.PLEC, JOS.NAZWA
            FROM PACJENT
                 INNER JOIN POBYT ON PACJENT.ID_PAC = POBYT.ID_PAC
                 INNER JOIN JOS ON JOS.IDK_JOS = POBYT.IDK_JOS
           WHERE TRUNC(MONTHS_BETWEEN(POBYT.DT_OD, PACJENT.DATA_UR) / 12) > 65)
  SELECT NAZWA,
         SUM(K),
         SUM(M),
         SUM(SUMA)
    FROM (SELECT NAZWA,
                 K,
                 M,
                 K + M AS suma
            FROM dane PIVOT (COUNT(*) FOR PLEC IN ('M' AS K, 'K' AS M)))
GROUP BY ROLLUP(NAZWA)