0

我有一张这样的桌子

|   ids   | name     |  status    |
----------------------------------
|    1    | name1    |   true     |
|    2    | name2    |   true     |
|    3    | name1    |   true     |
|    4    | name4    |   true     |
|    5    | name1    |   false    |
|    6    | name2    |   false    |
|    8    | name1    |   false    |
|    9    | name1    |   true     |
|    10   | name1    |   false    |
|    11   | name1    |   false    |

我想获取where (name = name1 or name2) and count所有真实状态的行(例如,在表中 total_true_count=4 [即。所有这些 ids ids=1,2,3,9] 的行)和所有错误状态(例如,在表中total_false_count=5 ie. [all row of these ids=5,6,8,10,11] )所选行。

Output will be like this

$output=Array
                (
                    [total_true_count] => 4,
                    [total_false_sms] => 5,
                    [row_data]=>{row1,row2....}
                )

我尝试了计数功能,但它对我不起作用。谁能帮忙

4

1 回答 1

1

您可以用来array_agg对数组中的值进行分组,并用于FILTER限制馈送到的值COUNT(*)

WITH data(id, name, status) AS (
    VALUES (1, 'name1', TRUE)
         , (2, 'name2', TRUE)
         , (3, 'name1', TRUE)
         , (4, 'name4', TRUE)
         , (5, 'name1', FALSE)
         , (6, 'name2', FALSE)
         , (8, 'name1', FALSE)
         , (9, 'name1', TRUE)
         , (10, 'name1', FALSE)
         , (11, 'name1', FALSE)
)
SELECT array_agg(id) AS row_data -- or array_agg(data.*) if you want all columns
     , COUNT(*) FILTER (WHERE status)     AS total_count_true
     , COUNT(*) FILTER (WHERE NOT status) AS total_count_false
FROM data
WHERE name IN ('name1', 'name2')

返回

+---------------------+----------------+-----------------+
|row_data             |total_count_true|total_count_false|
+---------------------+----------------+-----------------+
|{1,2,3,5,6,8,9,10,11}|4               |5                |
+---------------------+----------------+-----------------+

或者,使用array_agg(data.*)

+----------------------------------------------+----------------+-----------------+
|row_data                                      |total_count_true|total_count_false|
+----------------------------------------------+----------------+-----------------+
|{"(1,name1,t)","(2,name2,t)",…,"(11,name1,f)"}|4               |5                |
+----------------------------------------------+----------------+-----------------+
于 2020-05-07T17:32:28.380 回答