内部连接两个表,使用roll up和order by和group by

时间:2016-09-01 10:23:24

标签: mysql sql database codeigniter

我被困在最后几天,真的不知道该怎么做。
我有一个数据库,有三个表来获取数据。我无法使用汇总与内部联接和订单。
我有以下查询返回结果。

SELECT  bb_catg.catg_name,
        bi_item_name,
        sum(bi_item_qty) as TotalQty,
        sum(bi_item_total) as Grandtotal
FROM bb_bill_items 
    inner join bb_items
    on  bb_bill_items.item_id = bb_items.item_id 
    inner join bb_catg 
    on bb_items.catg_id  = bb_catg.catg_id
    inner join bb_bill
    on bb_bill_items.bil_id  = bb_bill.bil_id
where dateandtime = '$date' and paymenttype = '$Status'
group by bb_bill_items.item_id
order by bb_catg.catg_name

结果

catg_name | bi_item_name | TotalQty | Grandtotal
------    | ------------ |--------- |-----------
PASTRIES  |Cupcake       |1         |270
PASTRIES  |Eclair        |1         |150
PASTRIES  |Mousse        |1         |350
           ----------
             total       |3         |770

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您可以针对您的解决方案更改以下查询:

SELECT  bb_catg.catg_name,bi_item_name,
        sum(bi_item_qty) as TotalQty,sum(bi_item_total) as Grandtotal
FROM bb_bill_items 
inner join bb_items
    on  bb_bill_items.item_id = bb_items.item_id 
inner join bb_catg 
on bb_items.catg_id  = bb_catg.catg_id
inner join bb_bill
    on bb_bill_items.bil_id  = bb_bill.bil_id
where dateandtime = '$date' and paymenttype = '$Status'
group by bb_catg.catg_name,bb_items.bi_item_name
order by bb_catg.catg_name

与您可以在Group By Clause中添加的其他列聚合函数。