MySQL选择案例 - 两个表之间的比较

时间:2016-11-30 13:13:49

标签: mysql sql select case

我有两张类似的表:

Table: case

---------------------------------------------------
| id |  company | managed |    time    |  client  |
---------------------------------------------------
| 1  |  apple   |   yes   | 1412643785 |    no    |
---------------------------------------------------
| 2  |  barilla |   no    | 1412643785 |    no    |
---------------------------------------------------
| 3  |  google  |   no    | 1412643785 |   yes    |
---------------------------------------------------
| 4  |  google  |   yes   | 1412643785 |   yes    |
---------------------------------------------------
| 5  |  google  |   no    | 1412643785 |   yes    |
---------------------------------------------------


Table: language

---------------------------
| id | company  |  lang   |
---------------------------
| 1  |  apple   |   EN    |
---------------------------
| 2  |  barilla |   IT    |
---------------------------
| 3  |  google  |   EN    |
---------------------------

我已经从这款平板电脑创建统计数据/图形,我每个月都会提取以下信息: *每月客户案例数 *每月管理的案件数量 *每月病例总数 *每月意大利公司的案例数

对于前三点,我没有任何问题,我已经提出了这个问题:

SELECT FROM_UNIXTIME(time, '%Y-%M') as 'Month', 
    COUNT(CASE WHEN client = 'yes' THEN 1 ELSE NULL END) as 'Reports of a customer,
    COUNT(CASE WHEN managed = 'yes' THEN 1 ELSE NULL END) as 'Managed cases',
    COUNT(id) as 'Total reports'
FROM case
GROUP BY FROM_UNIXTIME(time, '%Y-%M')
ORDER BY FROM_UNIXTIME(time, '%Y-%m')

但如何提取任何意大利公司管理的每月案例数量?

我尝试添加此部分查询但不会...

COUNT(CASE WHEN case.company = language.company AND language.lang = 'IT'  THEN 1 ELSE NULL END) as 'Italian Case',
你能帮帮我吗?谢谢

1 个答案:

答案 0 :(得分:1)

你的想法是正确的,只需加入附加表:

SELECT FROM_UNIXTIME(t.time, '%Y-%M') as 'Month', 
    COUNT(CASE WHEN t.client = 'yes' THEN 1 END) as 'Reports of a customer',
    COUNT(CASE WHEN t.managed = 'yes' THEN 1 END) as 'Managed cases',
    COUNT(t.id) as 'Total reports',
    COUNT(CASE WHEN language.lang = 'IT'  THEN 1 END) as 'Italian Case',
FROM case t
JOIN language ON language.company = t.company
GROUP BY FROM_UNIXTIME(t.time, '%Y-%M')
ORDER BY FROM_UNIXTIME(t.time, '%Y-%m')

请注意,我从您的案例中删除了ELSE NULL,因为它是默认值。