Postgresql中平均有3个顶级值的SQL子查询

时间:2014-08-22 11:58:00

标签: sql postgresql postgresql-9.1

我需要一些帮助来解决查询以计算具有3个最后舒张期张力(TAD)的平均值的患者(ID)。 90。

我尝试了几种不同错误的嵌套子查询。

这是我完成的最后一个版本:

SELECT CENTRO, COUNT ( DISTINCT ID )
FROM
(
    SELECT PAC.CENTRO, PAC.ID, T.TAD
    FROM IDDPAC PAC,
    (
        SELECT AVG(TA.TAD) TAD
        FROM
        (
            SELECT
            TEXT_TO_NUMBER ( PAG.TEXTO ) TAD
            FROM IDDPAG PAG, DATE D
            WHERE TRIM  ( PAG.DGP )='AH'
            AND PAG.ID=T.ID
            AND PAG.FECHA=D.OMI
            AND D.TIME_DATE::DATE BETWEEN DATE '2012-01-01'
            AND DATE '2012-12-31'
            ORDER BY PAG.FECHA DESC LIMIT 3
        ) TA
    ) T
    WHERE PAC.CENTRO='10040110' AND T.ID = PAC.ID
    GROUP BY PAC.CENTRO , PAC.ID
)
A
WHERE T.TAD < 90
GROUP BY CENTRO

我收到以下错误:

ERROR:  falta una entrada para la tabla «t» en la cláusula FROM
LINE 31:             AND PAG.ID=T.ID
                                ^
********** Error **********

翻译:

ERROR:  missing an entry for the table «t» in the clause FROM
LINE 31:             AND PAG.ID=T.ID
                                ^
********** Error **********

2 个答案:

答案 0 :(得分:0)

问题是,正如错误所示,“T”未在请求的位置定义。您的错误位于最里面的子查询中:

        SELECT
        TEXT_TO_NUMBER ( PAG.TEXTO ) TAD
        FROM IDDPAG PAG, DATE D
        WHERE TRIM  ( PAG.DGP )='AH'
        AND PAG.ID=T.ID
        AND PAG.FECHA=D.OMI
        AND D.TIME_DATE::DATE BETWEEN DATE '2012-01-01'
        AND DATE '2012-12-31'
        ORDER BY PAG.FECHA DESC LIMIT 3

但是此处定义的T没有在PAG.ID=T.ID子句的WHERE部分中使用。你的意思是加入名为T的桌子吗?或者您的意思是使用D.ID代替?

答案 1 :(得分:0)

要获取最后三个值的平均值,请使用row_number()枚举值。然后选择最后三个并取平均值。这为您提供了患者级信息:

    SELECT PAC.CENTRO, PAG.ID, AVG(TA.TAD) AS TAD
    FROM (SELECT PAG.ID, TEXT_TO_NUMBER ( PAG.TEXTO ) as TAD,
                 ROW_NUMBER() OVER (PARTITION BY PAG.ID ORDER BY D.TIME_DATE DESC) as seqnum
          FROM IDDPAG PAG JOIN
               DATE D
               ON PAG.FECHA = D.OMI JOIN
               IDDPAC PAC
               ON PAC.ID = PAG.ID
          WHERE TRIM  ( PAG.DGP )='AH' AND
                D.TIME_DATE::DATE BETWEEN DATE '2012-01-01' AND DATE '2012-12-31'
         ) TA
    WHERE SEQNUM <= 3
    GROUP BY PAC.CENTRO, PAD.ID
    HAVING AVG(TA.TAD) < 90;

centro的计数只是:

  SELECT CENTRO, COUNT(*)
  FROM (SELECT PAC.CENTRO, PAG.ID, AVG(TA.TAD) AS TAD
        FROM (SELECT PAG.ID, TEXT_TO_NUMBER ( PAG.TEXTO ) as TAD,
                     ROW_NUMBER() OVER (PARTITION BY PAG.ID ORDER BY D.TIME_DATE DESC) as seqnum
              FROM IDDPAG PAG JOIN
                   DATE D
                   ON PAG.FECHA = D.OMI JOIN
                   IDDPAC PAC
                   ON PAC.ID = PAG.ID
              WHERE TRIM  ( PAG.DGP )='AH' AND
                    D.TIME_DATE::DATE BETWEEN DATE '2012-01-01' AND DATE '2012-12-31'
             ) TA
        WHERE SEQNUM <= 3
        GROUP BY PAC.CENTRO, PAD.ID
        HAVING AVG(TA.TAD) < 90
       ) TA
  GROUP BY CENTRO;