楼主在做一个智慧工地的产品,需要对工人进行一些数据统计,比如要统计导入人员数量小于30的工地,SQL应该怎么写呢?
  首先了解一下数据结构,工地分三张表,四级层级关系,Organization表存储区域、城市两级,Projects表存储项目,Stages表存储分期;还有一个worker表存储人员。这4张表外键分别保存的上级表的id。
  要查出工人小于30的工地大体步骤如下:
  1、找出小于30人的工地分期id;
  2、根据分期id外连接查出对应的工地全称;
  3、根据工地的4级进行分组排序。

  具体SQL如下:

SELECT
    org.NAME 区域名称,
    city.NAME 城市名称,
    pr.projectName 项目名称,
    st.stageName 分期名称,
    ws.wcount 工人数量
FROM
    Stages st
    LEFT JOIN Projects pr ON st.projectMdid = pr.projectMdid
    LEFT JOIN Organization city ON city.mdid = pr.bizOrgMdid
    LEFT JOIN Organization org ON org.mdid = city.parentMdid
    LEFT JOIN ( SELECT w.stageMdid stageMdid, count( * ) wcount FROM worker w WHERE w.deleteflag = 0 GROUP BY w.stageMdid ) ws ON st.stageMdid = ws.stageMdid
WHERE
    st.stageMdid IN ( SELECT w.stageMdid FROM worker w WHERE w.deleteflag = 0 GROUP BY w.stageMdid HAVING COUNT( * ) < 30 )
ORDER BY
    org.NAME,
    city.NAME,
    pr.projectName

  查出的数据:

   当然了,SQL有可以优化的地方,因为只是线下查询一下,对效率没有要求,楼主就这么按照思路写的流水账。

12-27 22:28