Mysql查询查找不同列的计数

时间:2017-06-20 17:47:09

标签: php mysql mysqli

我有一张桌子: tbl_uesr

admission     discharge        name       unit

2017-05-07    2017-05-10       Deepu      100
2017-05-07    2017-05-09       Nisanth    100
2017-05-08    2017-05-10       Ragesh     100
2017-05-15    2017-05-20       Vidhu      100
2017-05-15    2017-05-21       Reshma     100

2017-05-15    2017-05-21       Sneha      104
2017-06-01    2017-06-10       Lekshmi    104
2017-06-03    2017-06-10       Nidhin     104
2017-06-17    2017-06-20       Vineesh    104

2017-05-07    2017-05-08       Rithun     107

上表描述了特定用户的admission datedischarge date及其unit。从上表中我必须找到给定的dateunit how many admission happenedhow many discharge happened

例如,在 2017-05-07 上, 2单元100 1单元107入场任何单位都没有放电

因此,在我的搜索结果中,我希望所有dates(录取日期和出院日期),number of admissionnumber of discharge

预期结果

Date           no_admission     no_discharge     unit

2017-05-07     2                0                100
2017-05-07     1                0                107
2017-05-08     1                0                100
2017-05-08     0                1                107
2017-05-15     2                0                100 
2017-05-15     1                0                104 
2017-05-09     0                1                100
2017-05-10     0                3                100
2017-05-20     0                1                100
2017-05-21     0                1                100
2017-05-21     0                1                104
2017-06-01     1                0                104
2017-06-03     1                0                104
2017-06-17     1                0                104
2017-06-10     0                2                104
2017-06-20     0                1                104

我尝试了什么

我不知道如上所述将所有日期都带到新表(结果)。我试图通过以下方式找到no_admission:

SELECT admission as date, count(name) as no_admission, unit FROMtbl_user GROUP BY admission

并试图通过以下方式找到no_discharge:

SELECT discharge as date, count(name) as no_discharge, unit FROMtbl_user GROUP BY discharge

但仍然无法按预期找到我的结果..

请帮我找到预期的结果..

1 个答案:

答案 0 :(得分:2)

这里棘手的部分是你有两个日期在同一条线上,有时需要计算;对于每个日期,有时不是并且确实需要在两条不同的行上。实现此目的的一种方法是使用两个select语句取消日期,然后求和。

SELECT d.mdate, sum(d.no_Admission) as No_Admission, sum(d.no_Discharge) as no_Discharge, d.unit
FROM (SELECT admission as mdate, 1 as No_Admission, 0 as No_Discharge, unit
      FROM tbl_user
      UNION ALL

      SELECT discharge as mdate, 0 as No_Admission, 1 as No_Discharge, unit
      FROM tbl_user) d
GROUP BY d.mdate, d.unit

的另一种方式是创建一个不同的日期列表,然后根据日期加入相应的记录。以下是未经测试的,我不确定由于与tlb_user的多次连接,记录是否会人为地夸大计数。我想不是;但不是积极的。

SELECT mdate
     , count(A.Admission) as No_Admission
     , count(D.Discharge) as No_Discharge
     , coalesce(A.Unit, D.Unit) as unit
FROM (SELECT admission as mdate FROM tbl_user
      UNION 
      SELECT discharge as mdate FROM tbl_user) d
LEFT JOIN tbl_user A
 on d.mDate = A.admission
LEFT JOIN tbl_user D
 on d.mdate = D.Discharge
 and A.Unit = D.Unit
GROUP BY mdate, coalsece(A.Unit, D.Unit)