在别名中使用SUM

时间:2016-04-29 06:04:35

标签: php sql

我想在别名中使用SUM函数 请看下面的代码,希望你能理解:

     SELECT PATIENTS.NAME,
       PATIENTS.FAMILY,
       COST.COST,
       COST.REALDATEYEAR,
       COST.REALDATEMONTH,
       COST.REALDATEDAY,
       CONTRACTS.ID,
       CONTRACTS.FRANSHIZ AS CO1,
       PATIENTS.COMPANY,
       CONTRACTS.COMPANY,
       COST.TYPE,
       TARRIFS.ID,
       TARRIFS.ACTION,
       TARRIFS.COST       AS CO
  FROM PATIENTS
 INNER JOIN COST
 INNER JOIN CONTRACTS
 INNER JOIN TARRIFS
    ON PATIENTS.SINGLE_ID = COST.SINGLE_ID
   AND COST.TYPE = TARRIFS.ID
   AND CONTRACTS.ID = PATIENTS.COMPANY

我想将SUM用于co1和co,

1 个答案:

答案 0 :(得分:0)

使用GROUP BY时,您需要使用SUM

你的查询是这样的。

SELECT PATIENTS.NAME,
       PATIENTS.FAMILY,
       COST.COST,
       COST.REALDATEYEAR,
       COST.REALDATEMONTH,
       COST.REALDATEDAY,
       CONTRACTS.ID,
       SUM(CONTRACTS.FRANSHIZ) AS CO1,
       PATIENTS.COMPANY,
       CONTRACTS.COMPANY,
       COST.TYPE,
       TARRIFS.ID,
       TARRIFS.ACTION,
       TARRIFS.COST AS CO
  FROM PATIENTS
 INNER JOIN COST
 INNER JOIN CONTRACTS
 INNER JOIN TARRIFS
    ON PATIENTS.SINGLE_ID = COST.SINGLE_ID
   AND COST.TYPE = TARRIFS.ID
   AND CONTRACTS.ID = PATIENTS.COMPANY
 GROUP BY CONTRACTS.FRANSHIZ