MYSQL使用UNION选择查询以合并来自共享相同密钥的三个表的数据

时间:2012-01-11 21:11:41

标签: mysql subquery union

我的查询是这样构建的,但我没有得到预期的结果。我有像

这样的表格
  1. company_group- group_company_id,group_company_name
  2. store - store_id,store_name
  3. sales_report- sales_id,group_company_id,store_id,sales_4,vat_4
  4. warehouse_sales - warehouse_sales_id,warehouse_sales_id(FK-group_company_id),store_name(FK-store_id),日期,sales_four_percent
  5. Stock_recpt- Stock_recpt_id,group_company_id,receipt_date,input_vat_4
  6. 这个查询得到的结果如

    company_group store_name月sales_4 vat_4 input_vat

    SELECT firm, store_name, MONTH, sales_4, vat_4, input_vat_4
    FROM (select `company_group`.`group_company_name`as firm,`store`.`store_name`as store_name, MONTHNAME( receipt_date ) AS MONTH,0 AS sales_4, 0 as vat_4,sum(`input_vat_4_percent`)as input_vat_4 from
    company_group,store, Stock_recpt
    WHERE `company_group`.`group_company_id` = `Stock_recpt`.`group_company_id`and `store`.`store_id` = `Stock_recpt`.`store_id` and  `Stock_recpt`.`purchase_type` = 'purchase_4_percent' 
    UNION
    
    SELECT `company_group`.`group_company_name`as firm , `store`.`store_name`as store_name , MONTHNAME(date) AS MONTH , sum( `warehouse_sales`.`sales_four_percent`)as sales_4, sum( `warehouse_sales`.`vat_four_percent` ) AS vat_4, 0 as input_vat_4 
    
    from company_group,store, warehouse_sales
    WHERE `company_group`.`group_company_id` = `warehouse_sales`.`firm_name`and `store`.`store_id` = `warehouse_sales`.`store_name`  
    
    UNION
    
    SELECT `company_group`.`group_company_name` as firm, `store`.`store_name`as store_name,MONTHNAME( sale_date ) AS MONTH, sum( `sales_report`.`sales_four_percent`)as sales_4, sum( `sales_report`.`vat_four_percent` ) AS vat_4,0 as input_vat_4
    
    FROM company_group,store, sales_report
    WHERE `company_group`.`group_company_id` = `sales_report`.`group_company_id`and `store`.`store_id` = `sales_report`.`store_id`)a
    GROUP BY firm , store_name,`MONTH`
    

0 个答案:

没有答案