鍍金池/ 問答/PHP  Python  數(shù)據(jù)庫/ SQL如何完成多張表的報(bào)表?

SQL如何完成多張表的報(bào)表?

a b c d 共四表

  • a-> 用戶類型
  • b-> 用戶表
  • c-> 訂單表
  • d-> 訂單商品表 (一訂單對(duì)應(yīng)多個(gè)商品)
  1. a.id a.title
  2. b.uid b.aid
  3. c.oid, c.uid, c.create_time
  4. d.id d.oid d.goods_name d.num d.price

需求-統(tǒng)計(jì)分析

條件 用戶類型 下單時(shí)間

報(bào)表格式

\ 小米3 小米6 蘋果4 蘋果6 蘋果X 金額
用戶類型1 數(shù)量 數(shù)量 .. .. .. 合計(jì)
用戶類型2
用戶類型3
合計(jì) 合計(jì) 合計(jì) ... ... ... 總計(jì)
回答
編輯回答
孤酒

思路: 先查出注冊(cè)用記的類型, 然后再用戶類型的數(shù)組再循環(huán)訂單中所有的商品.

//語句可查出第一列(用戶類型) 最后一列(金額)
select m.uid,a.id,
                    sum((select 
                        sum((select sum(p.num * p.price) from {$pfix}d p where p.oid = o.id)
                    ) as user_amount
                    from {$pfix}c o where o.uid = m.uid)) as user_order_total
                    from {$pfix}b m 
                    JOIN {$pfix}a a ON m.aid = a.id
                    group by a.id
//查出所以訂單的商品類型
select product_id,product_name from {$pfix}d group by product_id
//循環(huán)出上列表格
        foreach ($data as $key => $value) { //AND o.create_time > 1516204800 下單時(shí)間條件
            $userSql = "select o.id from {$pfix}b m 
                        RIGHT JOIN {$pfix}c o ON o.uid = m.uid where m.aid= {$value ['id']} {$where}
            "; //查出用戶類型下所有用戶訂單
            $userData = $model->query($userSql);
            if(!empty($userData)) {
                
                $userWhere = implode(',', array_column($userData, 'id'));
                foreach ($productData as $k => $v) {
                    $amountSql = "select sum(num) as amount_total from {$pfix}d where product_id = {$v ['product_id']} AND oid IN({$userWhere})";
                    $amount = $model->query($amountSql);
                    $amount = $amount [0]['amount_total'];
                    $data [$key]['product'][$v ['product_id']] = array('amount_total' => $amount);
                }
                dump($productData);
            }
        }
2017年11月23日 07:40
編輯回答
鐧簞噯

用pivot。
Oracle官方文檔

2017年6月9日 23:52