【问题标题】:Combining two rows from the same table and calculating total合并同一张表中的两行并计算总数
【发布时间】:2021-02-02 06:13:42
【问题描述】:

我有一个包含两列的表格,如下所示:

total | measure
________________
1     | private vehicle use
4     | private car use
7     | other

我想将前两行合并为一行,将合并行的度量 (strEUCategory) 重命名为“私人车辆使用”。我也想合并总数。 我研究了 CASE 和 PIVOT,但在计算总数的同时无法让它工作。

这是我的查询。

SELECT  count(m.strEUCategory) as total , m.strEUCategory as measure
                from  laqm2_AQAP_measures  m
                where m.strYearIntroduced <=2020 and m.strCompletionYear >=2020
                group by m.strEUCategory
                order by m.strEUCategory 

【问题讨论】:

标签: sql string count mariadb case


【解决方案1】:

我想你想要一个case 表达式和聚合:

select
    case when strEUCategory = 'private car use' then 'private vehicule use' else strEUCategory end as measure,
    count(*) cnt
from laqm2_AQAP_measures
where strYearIntroduced <= 2020 and strCompletionYear >= 2020
group by measure
order by measure

如果您想对新类别名称进行更多控制,那么:

select
    case when strEUCategory in ('private car use', 'private vehicle use')  
        then 'Private Vehicule Use' 
        else strEUCategory 
    end as measure,
    count(*) cnt
from laqm2_AQAP_measures
where strYearIntroduced <= 2020 and strCompletionYear >= 2020
group by measure
order by measure

【讨论】:

  • 这行得通,谢谢!但是,是否可以在该表达式中将行重命名为新名称?它目前是“私人车辆使用”,但我希望它显示为“私人车辆使用”
猜你喜欢
  • 1970-01-01
  • 2018-01-12
  • 1970-01-01
  • 1970-01-01
  • 2017-08-22
  • 1970-01-01
  • 2020-06-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多