如何从数据库中获取组合数?

时间:2016-02-04 08:43:19

标签: mysql sql

如何从数据库中获取组合数?

我必须使用数据库表并希望获得组合计数。有人知道如何把它放在数据库查询中,因此我没有每次旅行的数据库请求吗?

行程

| ID | Driver | Date       |
|----|--------|------------|
| 1  | A      | 2015-12-15 |
| 2  | A      | 2015-12-16 |
| 3  | B      | 2015-12-17 |
| 4  | A      | 2015-12-18 |
| 5  | A      | 2015-12-19 |

乘客

| ID | PassengerID | TripID |
|----|-------------|--------|
| 1  | B           | 1      |
| 2  | C           | 1      |
| 3  | D           | 1      |
| 4  | B           | 2      |
| 5  | D           | 2      |
| 6  | A           | 3      |
| 7  | B           | 4      |
| 8  | D           | 4      |
| 9  | B           | 5      |
| 10 | C           | 5      |

预期结果

| Driver | B-C-D | B-D | A | B-C |
|--------|-------|-----|---|-----|
| A      | 1     | 2   | - | 1   |
| B      | -     | -   | 1 | -   |

替代

| Driver | Passengers | Count |
|--------|------------|-------|
| A      | B-C-D      | 1     |
| A      | B-D        | 2     |
| A      | B-C        | 1     |
| B      | A          | 1     |

有人有想法吗?

非常感谢!

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT Driver, Passengers, COUNT(*) AS `Count`
FROM (
  SELECT t.ID, t.Driver, 
         GROUP_CONCAT(p.PassengerID 
                      ORDER BY p.PassengerID 
                      SEPARATOR '-') AS Passengers
  FROM Trips AS t
  INNER JOIN Passengers AS p ON t.ID = p.TripID
  GROUP BY t.ID, t.Driver) AS t
GROUP BY Driver, Passengers

上述查询将生成替代结果集。另一个结果集只能使用动态sql来实现。

Demo here