子表状态

时间:2012-12-03 20:30:06

标签: mysql sql database

我有一张包含IDhouseIdTask的表格A.我有另一张包含IDTbleAIdDescriptionStatus的表格。

Table Structure

我想要计算所有任务,已完成的任务(所有状态都设置为“已完成”)和未完成的任务(其中所有状态未设置为“已完成”)

查看图像以获取样本:

提前致谢!

4 个答案:

答案 0 :(得分:0)

我似乎完全误读了这个问题。谢谢@poncha澄清它。您希望在按照房屋总结之前按任务进行汇总:

select HouseId,
       count(*) as NumTasks,
       sum(case when NotCompletedSubTask = 0 then 1 else 0 end) as Completed,
       sum(case when NotCompletedSubtask > 0 then 1 else 0 end) as NotCompleted
from (select b.TbleAId, a.HouseId
             sum(case when status = 'Completed' then 1 else 0 end) as CompletedSubTask,
             sum(case when status <> 'Completed' then 1 else 0 end) as NotCompletedSubTask
      from TableB b join
           TableA a
           on b.TbleAID = a.ID
      group by b.TbleAId, a.HouseId
     ) t
group by HouseId

答案 1 :(得分:0)

理解这个问题的方式:A.ID任务的ID B.ID子任务的ID B.TableAID是从子任务到其父任务的引用。

如果这个假设是正确的,那么我认为问题是关于计算所有子任务完成的所有任务 ...

有点复杂,但或多或​​少看起来应该是这样的,除非你打算在SQL之外使用临时表或代码:

SELECT
A.HouseID,
COUNT(DISTINCT A.ID) as `Total Task`,
SUM(IF(C.TableAID IS NOT NULL AND C.total=C.completed,1,0)) AS `Completed Tasks`,
SUM(IF(C.TableAID IS NOT NULL AND C.total=C.completed,0,1)) AS `Incomplete Tasks`
FROM A
LEFT JOIN (
  SELECT TableAID,COUNT(*) AS total, SUM(IF(status='Completed',1,0)) AS completed
  FROM B
  GROUP BY TableAID
  ) AS C ON A.ID=C.TableAID
GROUP BY A.HouseID

答案 2 :(得分:0)

SELECT
  HouseID,
  count(*) as Total_Tasks,
  Sum(Total_SubTask=Completed_SubTask) as Completed_Tasks,
  Sum(Total_SubTask<>Completed_SubTask) as Incomplete_Tasks
FROM
  TableA inner join (
    SELECT
      TbleAID,
      Count(*) as Total_SubTask,
      Sum(Status='Completed') as Completed_SubTask
    FROM TableB
    GROUP BY TbleAID) s on tablea.ID = s.TbleAID
GROUP BY HouseID

答案 3 :(得分:0)

这是另一种双重分组解决方案,它使用稍微不同的方法:

SELECT
  a.HouseID,
  COUNT(*)                        AS TotalTasks,
  COUNT(b.TaskStatus = 1 OR NULL) AS CompletedTasks,
  COUNT(b.TaskStatus < 1 OR NULL) AS InCompleteTasks
FROM TableA a
  INNER JOIN (
    SELECT
      TbleAID,
      AVG(CASE Status WHEN 'Completed' THEN 1 ELSE 0 END) AS TaskStatus
    FROM TableB
    GROUP BY TbleAID
  ) b ON a.ID = b.TbleAID
GROUP BY a.HouseID
;

基本上,它用文本状态替换文本状态:Completed为1,其他(s)为0。对于每个任务,计算平均状态。如果结果是1,则表示所有子任务也是1,即完成,所以任务也完成了。

如果至少有一个子任务未完成,则平均值将小于1,从而表明整个任务不完整。

您可以尝试此解决方案at SQL Fiddle