2016-01-26 140 views
1

我想向表中添加其他(缺失)行。 現有情況:我有一張病人表,其中有一個註冊日期,我計算了病人已經註冊了多長時間(「TimeInProgram」)。現在,我彙總了這一點,以獲取當前處於此期間的患者人數(請參閱計數 - >屬性「患者」)。最後,我總結了一個窗口函數來獲取在特定時期內已經有WERE的患者人數。SQL:添加缺少的行

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以下行的患者在以下row.You的PatientsCounterInTime的值可以看到的問題:有一些「 TimeInProgram「 - 周如第4周或第5周缺失,因爲此時沒有患者在此期間。所以我想添加缺少的行。 「PatientsCounterInTime」的值在第4周,第5周應爲162.「患者」當然爲0.

我使用HANA作爲數據庫。

提前致以親切的問候和感謝。

UPDATE:

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的值。)

+2

您需要一個包含所有星期的日曆表,基本上是一個單列,其中包含1到48,並且在該列上加上LEFT JOIN – Mihai

+1

除了Mihai所說的內容之外,您還必須使用LEAD或LAG來獲取最後一個部分計數器時間加入時(SINCE在離開後會有一個空值) – sagi

+0

謝謝你的幫助!我加入了桌面並更新了上面的帖子。我不確定現在如何使用LEAD/LAG填寫缺席專欄的數據。任何提示再次? @sagi – ScientiaEtVeritas

回答

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) 

將是巨大的,如果你可以發送表中創建報表+些插入的數據,所以我可能是強麥,以幫助你。