我有三张桌子:
// priorities // statuses // projects
+----+--------+ +----+-------------+ +----+------+--------+----------+
| ID | NAME | | ID | STATUS NAME | | ID | NAME | STATUS | PRIORITY |
+----+--------+ +----+-------------+ +----+------+--------+----------+
| 1 | Normal | | 1 | Pending | | 1 | a | 1 | 3 |
+----+--------+ +----+-------------+ +----+------+--------+----------+
| 2 | High | | 2 | In Progress | | 2 | b | 1 | 1 |
+----+--------+ +----+-------------+ +----+------+--------+----------+
| 3 | Urgent | | 3 | c | 2 | 1 |
+----+--------+ +----+------+--------+----------+
| 4 | d | 1 | 2 |
+----+------+--------+----------+
我需要创建一个view
,其中显示有projects
个status
1
和1
的优先级,有多少人status
{1}} 1
,优先级2
,有status
1
,优先级3
,等等。< / p>
这应该遍历每个状态,然后是每个优先级,然后计算适用于标准的项目。
视图应该包含如下值:
// VIEW (stats)
+--------+----------+-------+
| STATUS | PRIORITY | COUNT |
+--------+----------+-------+
| 1 | 1 | 1 |
+--------+----------+-------+
| 1 | 2 | 1 |
+--------+----------+-------+
| 1 | 3 | 1 |
+--------+----------+-------+
| 2 | 1 | 1 |
+--------+----------+-------+
| 2 | 2 | 0 |
+--------+----------+-------+
| 2 | 3 | 0 |
+--------+----------+-------+
此观点是,我可以调用,例如,有多少项目的状态为1
,优先级为3
,给出上述数据的答案应为1
使用下面的select语句我已经能够产生类似的结果,但它没有明确显示0
项目的状态为2
且优先级为{{1} }。我需要使用此3
值,与0
的任何其他值相同。
COUNT >= 1
我怎样才能创建一个包含所有优先级的VIEW&#39; ID,所有状态&#39; // my current select statement
CREATE VIEW stats
AS
SELECT P.STATUS, P.PRIORITY, COUNT(*) AS hits
FROM projects P
GROUP BY P.STATUS, P.PRIORITY
// does not show rows where COUNT = 0
的ID,和 0值?
答案 0 :(得分:1)
您需要生成所有行,然后获取每个行的计数。这是一个应该有效的查询:
SELECT s.status, p.priority, COUNT(pr.status) AS hits
FROM (SELECT DISTINCT status FROM projects) s CROSS JOIN
(SELECT DISTINCT priority FROM projects) p LEFT JOIN
project pr
ON pr.status = s.status and pr.priority = p.priority
GROUP BY s.status, p.priority;