单个选择查询中的多个和列,并按ID分组

时间:2017-11-08 12:29:34

标签: sql

PatientId   PatientName CashAmount  CreditAmount    CreditCardAmount
--------------------------------------------------------------------
1           AMALRAJ A        0               0            0
1           AMALRAJ A        0             100            0
1           AMALRAJ A        0            1500            0
1           AMALRAJ A     1459               0            0

我需要这样的结果:

PatientId   PatientName   CashAmount    CreditAmount    CreditCardAmount
-------------------------------------------------------------------------
1           AMALRAJ A        1459           1600                0     

2 个答案:

答案 0 :(得分:1)

SELECT
    PatientId,
    PatientName,
    SUM(CashAmount) AS CashAmount,
    SUM(CreditAmount) AS CreditAmount,
    SUM(CreditCardAmount) AS CreditCardAmount
FROM table_with_patients
GROUP BY PatientId, PatientName

答案 1 :(得分:0)

其他方式没有group by cluase:

SELECT DISTINCT
       PatientId,
       PatientName,
       SUM(CashAmount) OVER(PARTITION BY PatientId,
                                         PatientName) CashAmount,
       SUM(CreditAmount) OVER(PARTITION BY PatientId,
                                           PatientName) CreditAmount,
       SUM(CreditCardAmount) OVER(PARTITION BY PatientId,
                                               PatientName) CreditCardAmount
FROM table;

结果:

PatientId   PatientName CashAmount  CreditAmount    CreditCardAmount
1            AMALRAJ A  1459        1600             0