SQL:添加缺少的行

时间:2016-01-26 12:00:09

标签: sql database relational-database hana

我想在表中添加其他(缺少的)行。 现有情况:我有一个患者表,其中是注册日期,我计算患者已经在几周内注册了多长时间(" TimeInProgram")。现在我对此进行汇总以获得当前在此期间的患者数量(参见COUNT - >属性"患者")。最后,我总结了一个窗口函数,以获得在特定时期内已经存在的患者数量。

SELECT aggregation.*, SUM("Patients") OVER () "All", SUM("Patients") OVER (ORDER BY "TimeInProgram" DESC ROWS UNBOUNDED PRECEDING) "PatientsCounterInTime" FROM (
SELECT COUNT(DISTINCT "PatientID") "Patients", "TimeInProgram" FROM (
SELECT
    pat."PatientID",
    ROUND(((DAYS_BETWEEN(pat."RegisteredOnDate", NOW())+1)/7.0), 0, 'ROUND_UP') "TimeInProgram"
    FROM t_patient pat
    ORDER BY "PatientID"
) data
GROUP BY "TimeInProgram"
ORDER BY "TimeInProgram"
) aggregation

您可以在此处看到结果:

(PatientsCounterInTime PLUS Patients of the following row is the value of PatientsCounterInTime of the following row.)

PatientsCounterInTime PLUS以下行的患者是下一行的PatientsCounterInTime的值。您可以看到问题:有一些" TimeInProgram" -weeks缺失,如第4周或第5周,因为在那个时期没有病人。所以我想添加缺少的行。 " PatientsCounterInTime"的价值在第4周,第5周应该是162,并且"患者"当然是0。

我使用HANA作为数据库。

亲切的问候和提前谢谢。

更新:

  SELECT "TiP" "TimeInProgram", "Patients", "PatientsCounterInTime" FROM (
        SELECT aggregation.*, SUM("Patients") OVER () "All", SUM("Patients") OVER (ORDER BY "TimeInProgram" DESC ROWS UNBOUNDED PRECEDING) "PatientsCounterInTime" FROM (
        SELECT COUNT(DISTINCT "PatientID") "Patients", "TimeInProgram" FROM (
        SELECT
            pat."PatientID",
            ROUND(((DAYS_BETWEEN(pat."RegisteredOnDate", NOW())+1)/7.0), 0, 'ROUND_UP') "TimeInProgram"
            FROM "t_patient" pat
            ORDER BY "PatientID"
        ) data 
        GROUP BY "TimeInProgram"
        ORDER BY "TimeInProgram"
        ) aggregation
    )
    RIGHT JOIN "t_time_in_program" t ON "TimeInProgram" = t."TiP";

enter image description here

(PatientsCounterInTime PLUS以下行的患者是下一行的PatientsCounterInTime的值。)

1 个答案:

答案 0 :(得分:0)

您可以在“_SYS_BI”架构中找到时间表。 如果没有,here是有用的文章

以下是如何使用它的示例。假设您要显示从2000年到当前年份的时间段:

WITH dataset AS (
    Select '2016' as YEAR, '216' AS PATIENTS FROM DUMMY
    union all
    Select '2010' as YEAR, '200' AS PATIENTS FROM DUMMY 
)
SELECT 
        distinct tdim.year,
        case when dataset.PATIENTS is null then 0 else dataset.PATIENTS end  
    FROM "_SYS_BI"."M_TIME_DIMENSION_MONTH" tdim
left outer join  dataset on tdim.year = dataset.year
where tdim.year >=2000 and tdim.year <= YEAR(CURRENT_DATE)

如果您可以发送表创建语句+数据的一些插入,那就太棒了,所以我可能会帮助您更多。