dongyuqie4322 2016-06-27 10:40
浏览 27
已采纳

在Mysql中为Report报告三个表

I would like to produce report for airlines using

  1. Date Table
  2. Airline Table
  3. Route Table

My date table include series of date

    Entryid | Date 
    ----------------
       1    |2016-06-01
       2    |2016-06-02
       4    |2016-06-03
       5    |2016-06-04
       6    |2016-06-05
       7    |2016-06-06

My airline table include

id|name
---------
1 |Air1
2 |Air2
3 |Air3

and Route table:

id|date     |airline|routename
1|2016-06-01|1      |city1-city2
2|2016-06-01|1      |city1-city3
3|2016-06-01|2      |city1-city3
4|2016-06-02|2      |city1-city3
5|2016-06-02|2      |city1-city3
6|2016-06-04|2      |city1-city3
7|2016-06-04|2      |city1-city3
8|2016-06-04|1      |city1-city3

by using these three table I want to produce result as follow"

    Date   |Airline|totleroute
2016-06-01 |  Air1 | 2
2016-06-01 |  Air2 | 1
2016-06-02 |  Air1 | 0
2016-06-02 |  Air2 | 2
2016-06-03 |  Air1 | 0
2016-06-03 |  Air2 | 0
2016-06-04 |  Air1 | 1
2016-06-04 |  Air2 | 2

How to produce desired result from joining three tables?

  • 写回答

3条回答 默认 最新

  • du20150401 2016-06-27 10:48
    关注

    You can use a query like the following:

    SELECT d.`date`, t.`name`, COUNT(r.`routename`) AS TotalRoutes
    FROM `Date` AS d
    CROSS JOIN (
      SELECT DISTINCT r.`airline`, a.`name`
      FROM Route AS r 
      INNER JOIN Airline AS a ON r.airline = a.id
    ) AS t   
    LEFT JOIN Route AS r ON d.`date` = r.`date` AND t.`airline` = r.`airline`
    GROUP BY d.`date`, t.`airline`
    

    The CROSS JOIN is used in order to produce a result for each date - airline combination, as suggested by the sample output in the OP.

    Demo here

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 像这种代码要怎么跑起来?
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件