如何在其他列中显示1列总和

时间:2016-05-27 12:05:56

标签: mysql sql database database-design

我有一个表,其中不同的列显示不同的值。

我需要添加一个新列,在其他列的每一行中显示1列的总和。

这是我需要展示的内容。 enter image description here

我编写了以下查询,但它只在最后一列的每一行显示1

 select inStation.name TapInStation , outStation.name TapOutStation, 
        count(trx.passengerCount) PassengerCount, sum(trx.amount) Fare,

        (select sum(passengerCount) from transactions iTrx 
        where iTrx.ID = trx.ID) PassengerPercent                

     from transactions trx
     inner join 
     station inStation on inStation.ID = trx.fromStation 
     inner join
     station outStation on outStation.ID = trx.toStation

     GROUP BY 
     TapInStation, TapOutStation

1 个答案:

答案 0 :(得分:1)

如果需要总计,则删除关联子句。这可能会做你想要的:

 select inStation.name as TapInStation , outStation.name as TapOutStation, 
        count(trx.passengerCount) as PassengerCount,
        sum(trx.amount) as Fare,
        (select sum(passengerCount) from transactions iTrx) as PassengerPercent  

我不确定你为什么会打电话给"总计"像PassengerPercent这样的东西,但这应该返回整体总数。

我还怀疑你可能想要一个sum()用于前一个表达式。