将符号添加到选择查询输出的行值

时间:2018-05-24 15:31:03

标签: sql-server

我通过PIVOT转换了一个选择查询的结果,以获得如下所示的结果。所有值都是十进制(18,1)格式。

          || Item1 || Item2 || Item3
Avg_Price ||  234  ||  156  ||   73
%share    ||   17  ||   3   ||   35

我需要分别在行Avg_Price和%share中添加$和%符号。我怎样才能做到这一点?

编辑:按照@ B3S的要求在此处提供PIVOT查询。

select [Name],  [Item1],[Item2],[Item3],[Total]
from
  (
  select [Item_Type], [Name], value
  from (select [Item_Type],[Total Sales],[Share of Total Sales],[Average Price],[$0 to $99],[$100 to $199],[$200+]
    from    (SELECT [Item_Type],[Total Sales],CAST([Total Sales]*100.0/(SELECT SUM([Total Sales]) FROM My_DB.dbo.Sales_Data GROUP BY [Year],[Month]) AS DECIMAL(38,1)) [Share of Total Sales],[Average Price],[$0 to $99],[$100 to $199],[$200+] 
            FROM My_DB.dbo.Sales_Data
            union all
            select 'Total',SUM([Total Sales]),SUM([Total Sales])*100.0/(SELECT SUM([Total Sales]) FROM My_DB.dbo.Sales_Data GROUP BY [Year],[Month]) [Share of Total Sales],CAST(AVG([Average Price]) AS DECIMAL(38,1)),SUM([$0 to $99]),SUM([$100 to $199]),SUM([$200+])
            from My_DB.dbo.Sales_Data
            GROUP BY [Year],[Month]) d
    ) e
  unpivot
  (
    value for [Name] in ([Total Sales],[Share of Total Sales],[Average Price],[$0 to $99],[$100 to $199],[$200+])
  ) unpiv
) src
pivot
(
  sum(value)
  for [Item_Type] in ( [Item1],[Item2],[Item3],[Total])
) piv;

编辑:这不是一个重复的问题。对于这里指出的问题,这是一个不同的问题。我发布了这个问题,以寻求一种有效的方法来连续更新值,而不是查询每个值并附加它。

1 个答案:

答案 0 :(得分:1)

用一些字符串操作包裹你的[Item1]等。

declare @i int = 1
select '$' + convert(varchar, @i * 1.00)
select convert(varchar, @i) + '%'

您可能需要以下内容:

SELECT [Name], 
CASE WHEN [Name] = 'Avg_Price' THEN '$' + convert(varchar, [Item1] * 1.00) 
ELSE convert(varchar, [Item1]) + '%'
END AS [Item1],
CASE WHEN [Name] = 'Avg_Price' THEN '$' + convert(varchar, [Item2] * 1.00) 
ELSE convert(varchar, [Item2]) + '%'
END AS [Item2],
... etc...