根据CASE和GROUP BY结果第2部分创建一个新列

时间:2018-03-12 17:42:50

标签: sql mariadb

上一个问题:Make a new column based from CASE and GROUP BY result

从上一个问题我得到了如下结果

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

查询如下(感谢Gordon Linoff's answer):

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

现在,我还有其他问题。在列id_laporan_rekomendasi的左侧,有一个名为id_laporan的列,因此该表将如下所示。

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

我需要再次分组id_laporan并添加一个名为test2的新列,就像来自列test的列至少具有值0一样,结果将是{ {1}},如果除0之外没有其他值(例如0),则会在1列中为我们提供值1

我尝试过很多可能的问题:比如

test2

但它给了我结果

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

我将最大值更改为+------------+--------------------+ | id_laporan | MAX( t2.test = 1 ) | +------------+--------------------+ | 3 | 1 | | 7 | 1 | | 8 | 1 | +------------+--------------------+ ,它给我的结果如下:

MAX (t2.test = 0 )

我期待结果如下:

+------------+--------------------+
| id_laporan | MAX( t2.test = 0 ) |
+------------+--------------------+
|          3 |                  1 |
|          7 |                  0 |
|          8 |                  0 |
+------------+--------------------+

1 个答案:

答案 0 :(得分:0)

我终于得到了解决方案,

我只是将assert array_nan_close( np.array([1.3, np.nan, 3.4, np.nan]), np.array([1.3000001, 2, 3.4, 4]) ) assert not array_nan_close( np.array([1.1, 4.0, 3.5, np.nan]), np.array([1, 2, 3, 4]) ) 函数更改为MAX函数,所以它就像

MIN

完整查询

MIN( t2.test = 1 )

使用MIN功能,当列SELECT t2.id_laporan, MIN( t2.test = 1 ) FROM (SELECT t1.id_laporan, t1.id_laporan_rekomendasi, MAX( t1.status = 3 ) as test FROM test t1 GROUP BY t1.id_laporan_rekomendasi) t2 GROUP BY t2.id_laporan 的值低于0时,它将返回test