mysql - 查询中的层次结构以获得唯一计数

标签 mysql self-join

我有一个表来跟踪当前工作和工作状态。因此,在我的表列“当前工作”中捕获产品名称以及在该产品上完成的不同任务。

如果工作有子事件,则“工作父名称”列将填入“当前工作”,否则如果工作是独立的,则该列保持空白。因此,只需在工作级别或子事件级别进行一次计数,因此不能完全在分层路径中使用。

“状态”列随工作或子工作的进度更新。

![Work Table

现在,由于数据结构不正确,我发现计算产品的“进行中”状态有点困难。因此,如果工作下的任何工作或子事件的状态为进行中,我想将工作计为进行中

所以我正在寻找的输出如下:

![![![enter image description here

我尝试进行自加入,但由于子事件相同,我得到了错误的结果。他们有什么方法可以让我从这种类型的数据集中获得结果吗?

最佳答案

好吧...我对你的问题有点困惑。如果您进行计数,产品 5 的进度不应该是 2 吗?或者您只是想获得 1(如果有任何进展)。

试试这个...

select w1.work as work, count(*) countInProgress
from work w1 
inner join work w2 on w1.work = w2.parent
where w2.status = 'In Progress'
group by w1.work

如果您还想包含父级的进度,则可以使用此选项。

select workItem, count(*) countInProgress from
(
select work, @workItem := if(parent is not null,parent,work) workItem
, status
from work
) t 
where status = 'In Progress'
group by workItem

无论如何,这个问题有点不清楚。产品 2 如何有一个在制品任务“进行中”,但本身并未进行?

构建脚本

CREATE TABLE work (work varchar(20), parent varchar(20), status varchar(20));
INSERT INTO work VALUES
('Product 1',null,'In Progress'),
('Service', 'Product 1','Completed'),
('Delivery', 'Product 1', 'In Progress'),
('Transportation', 'Product 1', 'Completed'),
('Product 2',null,'In Progress'),
('Service', 'Product 2',''),
('Delivery', 'Product 2', 'In Progress'),
('Transportation', 'Product 2', ''),
('Product 3',null,'Completed'),
('Product 4',null,'In Progress'),
('Product 5',null,'In Progress'),
('Delivery', 'Product 5', 'In Progress'),
('Transportation', 'Product 5', 'In Progress')

如果你想玩的话,sqlfiddle 链接... http://sqlfiddle.com/#!9/e0fa02/15 希望这有帮助...

评论后编辑:

select w1.work as work
,if(w1.status = 'In Progress' or w2.status = 'In Progress',1,0) countInProgress
from work w1 
left join work w2 on w1.work = w2.parent
where w1.parent is null
group by w1.work

尝试一下...

此外,如果您想查看所有子项目都标记为“进行中”的位置

select w1.work as work
,if(w1.status = 'In Progress' or w2.status = 'In Progress',1,0) countInProgress
,@allInProgress := case when @allInProgress is null and w2.status = 'In Progress' then 1
                        when @allInProgress is null and (w2.status <> 'In Progress' or w2.status is null) then 0
                        when w2.status = 'In Progress' then @allInProgress * 1
                        when w2.status <> 'In Progress' then @allInProgress * 0
                        end allInProgress
from work w1 
left join work w2 on w1.work = w2.parent
where w1.parent is null
group by w1.work

关于mysql - 查询中的层次结构以获得唯一计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46508368/

相关文章:

php - 用户输入值 sql 的日期之间

PHP单选按钮mysql查询

mysql - 如何将 mysql 慢查询日志解析成有用的东西?

apache-spark - 增加读取 parquet 文件的并行度 - Spark 优化自连接

php - 如何在一张表mysql php中加入行

mysql - 带计算的自引用 SQL 查询

php - 如何将产品添加到购物车然后注册或登录

mysql - 在 MySql 中使用子查询更新

mysql - 写自连接 SQL 有什么更简洁的方法

mysql - 使用parent_id或child_id : Mysql选择整个团队