各类金额的和

时间:2014-07-19 14:15:19

标签: php sql database

我试图根据索赔类型在汇总表中累计索赔金额。

我的意思是每个员工一行,但有3列是"总车辆索赔","总医疗索赔"并且其他人声称"。

我该怎么做?

编辑(来自OP的评论):

$query="SELECT c.empid,u.userName, SUM(c_amount) AS total vehicle claim
        FROM claim c JOIN
             user u
             ON (c.empid = u.empid)
        WHERE c_type = 'Motorcycle' OR c_type='Car'
        GROUP by empid"

1 个答案:

答案 0 :(得分:-1)

这可以通过创建两个视图来完成。视图是虚拟表。这允许您创建一个虚拟表,其中empidSUM(c_amount)用于车辆索赔,另一个虚拟表用于医疗索赔的总和。

观点将是:

CREATE VIEW vehicle_claim AS
SELECT empid, SUM(c_amount) AS 'total vehicle claim'
FROM claim
WHERE c_type IN('Motorcycle', 'Car')
GROUP BY empid;

CREATE VIEW medical_claim AS
SELECT empid, SUM(c_amount) AS 'total medical claim'
FROM claim
WHERE c_type = 'Medical'
GROUP BY empid;

使用select语句:

SELECT *
FROM user u LEFT JOIN vehicle_claim v on u.empid = v.empid
    LEFT JOIN medical_claim m ON u.empid = m.empid

在此查询中,我选择了所有用户,并{I} LEFT JOIN我的两个视图。即使用户没有任何(车辆/医疗)索赔,我这样做也会获得数据。

Working SQL Fiddle