如何使用计数,'喜欢'并在单个查询中分组?

时间:2017-01-19 06:22:52

标签: sql postgresql conditional-aggregation

我需要像

这样的东西
SELECT sum(case when name LIKE 'nick-1%' then 1 end) as Count,
       name 
FROM dummytable 
GROUP BY CASE 
           WHEN name LIKE 'nick-1%' THEN 'nick' 
           WHEN name LIKE 'vicky-1%' THEN 'vicky' 
           ELSE NULL 
         END
Name  Count
nick    10
vicky   17

尼克意味着它应该包含像' nick%' vicky意味着它应该包含像' vicky%'

这样的名字

在我的查询中,我无法查看名称列,因为使用sum它要求我将其添加到group by但我无法将其添加到group by因为我正在使用它的功能

1 个答案:

答案 0 :(得分:0)

要解决您遇到的问题,您只需重复CASE GROUP BYSELECT所用的SELECT CASE WHEN name LIKE 'nick-1%' THEN 'nick' WHEN name LIKE 'vicky-1%' THEN 'vicky' ELSE NULL END AS Name, COUNT(*) AS Count FROM dummytable GROUP BY CASE WHEN name LIKE 'nick-1%' THEN 'nick' WHEN name LIKE 'vicky-1%' THEN 'vicky' ELSE NULL END 表达式:

SELECT

在原始查询中,您混合了两种类型的聚合。如果要对原始SELECT 'nick' AS Name, SUM(CASE WHEN name LIKE 'nick-1%' THEN 1 ELSE 0 END) AS Count FROM dummytable UNION ALL SELECT 'vicky', SUM(CASE WHEN name LIKE 'vicky-1%' THEN 1 ELSE 0 END) FROM dummytable 尝试执行的整个表使用条件聚合,可以使用以下查询:

from odoo import models, fields

class daily_transaction(models.Model):
    _name = 'daily.transaction'
    _description = 'Daily Transaction'

    subject = fields.Char('Subject', size=128, required = True)