如何得到表末尾的列总和

时间:2011-03-17 20:09:22

标签: mysql phpmyadmin

嗨,我现在从数据库中选择此项,我希望列s.fare s.commission 的总和作为总票价和总佣金在它下面的列结尾在新的row.i使用联盟,但我只想在最后一行这辆车票价总计

 SELECT s.fare, s.commission, o.driver, s._date, v.vehiclenumber, p.productname,
        s.source, s.destination, rs.routename, rd.routename, o.ownername
 FROM route AS rs, route AS rd, shipment AS s, product AS p, vehicle AS v,
      owner AS o
    WHERE s.vehicle = v.vehicleid
    AND s.source = rs.routeid
    AND v.owner = o.ownerid
    AND s.destination = rd.routeid
    AND s.product = p.productid
    AND v.vehiclenumber =  'nk-234'
    ORDER BY _date
    LIMIT 0 , 30

2 个答案:

答案 0 :(得分:1)

这非常棘手,因为您只想在LIMIT 0,30

中进行SUM
SELECT fare, commission, driver, _date, vehiclenumber, productname,
    source, destination, routename, routename, ownername
FROM
(
    SELECT *
    FROM 
    (
        SELECT 1 as Part,
            s.fare, s.commission, o.driver, s._date, v.vehiclenumber, p.productname,
            s.source, s.destination, rs.routename as rs_routename, rd.routename, o.ownername
        FROM route AS rs, route AS rd, shipment AS s, product AS p, vehicle AS v, owner AS o
        WHERE s.vehicle = v.vehicleid
        AND s.source = rs.routeid
        AND v.owner = o.ownerid
        AND s.destination = rd.routeid
        AND s.product = p.productid
        AND v.vehiclenumber =  'nk-234'
        ORDER BY _date
        LIMIT 0 , 30
    ) Part1
    UNION ALL
    SELECT 2 as Part,
        SUM(fare), SUM(commission), null, null, null, null,
        null, null, null, null, null
    FROM
    (
        SELECT
            s.fare, s.commission, o.driver, s._date, v.vehiclenumber, p.productname,
            s.source, s.destination, rs.routename as rs_routename, rd.routename, o.ownername
        FROM route AS rs, route AS rd, shipment AS s, product AS p, vehicle AS v, owner AS o
        WHERE s.vehicle = v.vehicleid
        AND s.source = rs.routeid
        AND v.owner = o.ownerid
        AND s.destination = rd.routeid
        AND s.product = p.productid
        AND v.vehiclenumber =  'nk-234'
        ORDER BY _date
        LIMIT 0 , 30
    ) Part2
) Joined
ORDER BY Part, _date

答案 1 :(得分:0)

使用类似的结构(只需添加必要的列而不是Price):

SELECT Price, 0 AS LastRow FROM Orders WHERE Price > 10
UNION
SELECT SUM(Price), 1 AS LastRow FROM Orders WHERE Price > 10
ORDER BY LastRow