1

我正在处理 SQL 查询

下面是输出:

PT_NO          PT_AGE         PT_SEX      DISEASE_CODE    PT_BILL_AMOUNT
--------     --------       --------     -----------     --------------   
1               50            M               52.01X         100.00
1               50            M               52.01X         100.00
1               50            M               52.01X         100.00
2               40            F               74.01          300.00
2               40            F               74.01          300.00
2               40            F               74.01          300.00

下面是表结构:

PATIENT(pt_no,pt_age,pt_sex,pt_bill_amount)
PATIENT_DISEASE(pt_no,disease_code)


SELECT 
  pt_no,pt_age,pt_sex
  ,patient_disease.disease_code
  ,patient.pt_bill_amount
from patient "patient"
    inner join patient_disease "patient_disease" 
    on patient.pt_no = patient_disease.pt_no

不知何故,我正在寻找一种不重复账单金额(仅 100 和 300 一次)的方法,这样当我对创建的上述视图求和时,我得到正确的账单金额为

PT_NO          PT_AGE         PT_SEX      DISEASE_CODE    PT_BILL_AMOUNT
--------     --------       --------     -----------     --------------   
1               50            M               52.01X         100.00
1               50            M               52.01X         0.00
1               50            M               52.01X         0.00
2               40            F               74.01          300.00
2               40            F               74.01          0.0
2               40            F               74.01          0.0

任何关于相同的输入都会有所帮助!

谢谢 !!!

4

2 回答 2

1

如果您希望这些行为空白,则可以使用row_number()

select pt_no, pt_age, pt_sex
    ,disease_code
    ,case 
      when rn = 1 
      then pt_bill_amount
      else 0.00
    end as pt_bill_amount
from
(
  SELECT 
    p.pt_no, p.pt_age, p.pt_sex
    , pd.disease_code
    , p.pt_bill_amount
    , row_number() over(partition by p.pt_no, pd.disease_code order by p.pt_no, pd.disease_code) rn
  from patient p
  inner join patient_disease pd
      on p.pt_no = pd.pt_no
) x
order by pt_no, disease_code, rn
于 2012-09-20T22:05:08.730 回答
0

您可以使用ROW_NUMBER函数为每组选择一行,用例函数仅显示该行中的金额。像那样:

SELECT pt_no,
       pt_age,
       pt_sex,
       patient_disease.disease_code,
       CASE
         WHEN ( ( Row_number()
                    OVER(
                      partition BY pt_no, pt_age, pt_sex,
                    patient_disease.disease_code
                      ORDER BY pt_no, pt_age, pt_sex,
                    patient_disease.disease_code) ) =
                1 ) THEN patient.pt_bill_amount
         ELSE 0
       END AS pt_bill_amount
FROM   patient "patient"
       INNER JOIN patient_disease "patient_disease"
               ON patient.pt_no = patient_disease.pt_no  
于 2012-09-20T22:07:57.963 回答