【问题标题】:CONCAT in SQL Server with a CASE WHEN troubleshootingSQL Server 中的 CONCAT 与 CASE WHEN 故障排除
【发布时间】:2021-08-24 10:24:26
【问题描述】:

需求结构

select
    Model,
    concat('',max(case when ranking = 1 then [Demand Structure] end ),round(cast(max(case when ranking = 1 then [Demand Structure] as float/count([Demand Structure]))*100,2),'%') top1_Demand_Structure,
    concat('',max(case when ranking = 2 then [Demand Structure] end ),round(cast(max(case when ranking = 2 then [Demand Structure] as float/count([Demand Structure]))*100,2),'%') top2_Demand_Structure
    --into #demand_structure_temp

from
    (
        SELECT 
        Model,
        [Demand Structure],
        COUNT(1)Demand_Structure_count,
        row_number() OVER(partition by model ORDER BY count(1) DESC) as Ranking
        FROM [EDW].[sio].[TB_R_SURVEY_IN_OPERATION] 
        group by Model,[Demand Structure]
    )a
group by model
order by 1;

round(cast(max(rank = 1 时的情况,然后 [需求结构] 为 float)round(cast(max(rank = 2 时的情况,然后 [需求结构] 为 float

这两个被sql server高亮显示为错误。

我打算显示此查询中返回的数字的百分比结果

结果示例:

|Top_1_Age|
-----------
|A 50%    |
|B 35%    |

有什么建议吗?

【问题讨论】:

  • 第 1 行和第 2 行的左括号 (() 比右括号 ()) 多。
  • [Demand Structure] as float 也没有意义; AS float 不是 CASE 表达式或 MAX 函数的有效语法。
  • 您(或更可能是其他人)会后悔始终使用三部分名称。连接应确定用于表引用的数据库。否则,数据库名称或环境的更改(例如在开发、测试和生产之间切换)需要更改您的代码。按顺序排列是另一个坏习惯。养成良好的习惯。

标签: sql sql-server tsql


【解决方案1】:

您的括号已关闭。在复杂的表达式中,我经常尝试对齐左括号和右括号,以便逻辑清晰:

select
    Model,
    concat('',
           max(case when ranking = 1 then [Demand Structure] end),
           round(cast(max(case when ranking = 1 then [Demand Structure] end
                         ) as float
                     ) /
                     count([Demand Structure]) * 100, 2
                 ), '%') as top1_Demand_Structure,
           concat('',
                  max(case when ranking = 2 then [Demand Structure] end ),
                  round(cast(max(case when ranking = 2 then [Demand Structure]
                                ) as float
                            ) /
                            count([Demand Structure]) * 100, 2
                       ), '%') as top2_Demand_Structure
    --into #demand_structure_temp

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    • 2013-09-03
    • 1970-01-01
    • 1970-01-01
    • 2016-07-08
    • 2011-08-27
    • 1970-01-01
    相关资源
    最近更新 更多