Make a new column based from CASE and GROUP BY result

一个人想着一个人 提交于 2020-01-15 03:58:12

问题


I have table like this called, table test:

+------------------------+--------+
| id_laporan_rekomendasi | status |
+------------------------+--------+
|                      1 |      2 |
|                      1 |      2 |
|                      1 |      2 |
|                      1 |      3 |
|                      2 |      2 |
|                      2 |      2 |
|                      2 |      2 |
|                      2 |      3 |
|                      3 |      2 |
|                      3 |      3 |
|                      4 |      2 |
|                      5 |      2 |
|                      5 |      3 |
|                      6 |      2 |
+------------------------+--------+

I want to group by id_laporan_rekomendasi and make a new column when in column status there is value 3. so if there is no value 3 in column status, then the value would be 0, but if there is value 3 than 1.

I expect the result would be like this

+------------------------+------+
| id_laporan_rekomendasi | test |
+------------------------+------+
|                      1 |    1 |
|                      2 |    1 |
|                      3 |    1 |
|                      4 |    0 |
|                      5 |    1 |
|                      6 |    0 |
+------------------------+------+

I have tried this query

SELECT t1.id_laporan_rekomendasi, 
COUNT(distinct case when t1.status = 3 then 1 else 0 end) as test
FROM test t1
GROUP BY t1.id_laporan_rekomendasi

But i got the result like below

+------------------------+------+
| id_laporan_rekomendasi | test |
+------------------------+------+
|                      1 |    2 |
|                      2 |    2 |
|                      3 |    2 |
|                      4 |    1 |
|                      5 |    2 |
|                      6 |    1 |
+------------------------+------+

Does anyone could help me with this table ?


回答1:


You are close. In MariaDB, you can simplify this to:

SELECT t1.id_laporan_rekomendasi, 
       MAX( t1.status = 3 ) as test
FROM test t1
GROUP BY t1.id_laporan_rekomendasi;

MariaDB (and MySQL) treat boolean expressions as numbers, with "1" for true and "0" for false. So this does what you want.



来源:https://stackoverflow.com/questions/49235114/make-a-new-column-based-from-case-and-group-by-result

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!