SQL QUERY - 不同的行编辑

时间:2012-09-20 21:51:05

标签: sql sql-server sql-server-2008 sql-server-2008-r2

我正在处理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

同样的任何输入都会有所帮助!!!

谢谢!!!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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