如何选择查询

时间:2014-10-25 04:22:07

标签: mysql select

我有一个名为tes的表格视图。

    +--------------+--------------+------+-----+---------+-------+
    | Field        | Type         | Null | Key | Default | Extra |
    +--------------+--------------+------+-----+---------+-------+
    | id_oba       | int(11)      | NO   |     | NULL    |       |
    | nama_obat    | varchar(120) | NO   |     | NULL    |       |
    | satuan       | varchar(20)  | YES  |     | NULL    |       |
    | stok_awal    | int(5)       | YES  |     | NULL    |       |
    | persediaan   | int(5)       | YES  |     | NULL    |       |
    | nama_suplier | varchar(30)  | NO   |     | NULL    |       |
    | pemakaian    | int(4)       | NO   |     | NULL    |       |
    | tanggal      | date         | YES  |     | NULL    |       |
    +--------------+--------------+------+-----+---------+-------+

执行时:

select id_oba, nama_obat, satuan, stok_awal, sum(pemakaian) AS pemakaian, persediaan, 
from tes group by id_oba;

我得到了这个结果:

    +--------+-----------+--------+-----------+-----------+------------+
    | id_oba | nama_obat | satuan | stok_awal | pemakaian | persediaan |
    +--------+-----------+--------+-----------+-----------+------------+
    |      1 | Paramex   | Botol  |        30 |        40 |          5 |       
    |      2 | Oskadon   | Botol  |        30 |        41 |         27 |      
    |      3 | Lindon    | Botol  |        31 |        30 |          4 |      
    +--------+-----------+--------+-----------+-----------+------------+

如何修改我的查询以获得这样的结果?

    +--------+-----------+--------+-----------+-----------+------------+-------+
    | id_oba | nama_obat | satuan | stok_awal | pemakaian | persediaan | total |
    +--------+-----------+--------+-----------+-----------+------------+-------+
    |      1 | Paramex   | Botol  |        30 |        40 |          5 | 45    |      
    |      2 | Oskadon   | Botol  |        30 |        41 |         27 | 67    |
    |      3 | Lindon    | Botol  |        31 |        30 |          4 | 34    |
    +--------+-----------+--------+-----------+-----------+------------+-------+

请帮我解决我的问题。

感谢。

1 个答案:

答案 0 :(得分:0)

像这样改变

select id_oba, nama_obat, satuan, stok_awal, sum(pemakaian) AS pemakaian,
persediaan,(sum(pemakaian)+persediaan) as total from tes group by id_oba;