ROLLUP,总计不同的四舍五入

时间:2018-02-07 07:09:20

标签: sql sql-server sql-server-2014 common-table-expression rollup

相关:Calculate group result and merge it with details

问题是我想要总计不同的舍入精度。请考虑以下代码:

DECLARE @tblStates AS Table
(
    StateName VARCHAR(50),
    Value1 DECIMAL(5,2),
    Value2 DECIMAL(5,2),
    Value3 DECIMAL(5,2)
)   

INSERT INTO @tblStates VALUES('State1',103,23,3)
INSERT INTO @tblStates VALUES('State2',105,32,12)
INSERT INTO @tblStates VALUES('State3',150,2,23)
INSERT INTO @tblStates VALUES('State4',50,10,8)
INSERT INTO @tblStates VALUES('State5',80,22,1)
INSERT INTO @tblStates VALUES('State6',20,18,45)

DECLARE @tblStatesGroups AS Table
(
    [Group] VARCHAR(50),
    [State] VARCHAR(50)
)   

INSERT INTO @tblStatesGroups VALUES('Group1','State1')
INSERT INTO @tblStatesGroups VALUES('Group1','State2')
INSERT INTO @tblStatesGroups VALUES('Group1','State3')
INSERT INTO @tblStatesGroups VALUES('Group2','State4')
INSERT INTO @tblStatesGroups VALUES('Group2','State5')
INSERT INTO @tblStatesGroups VALUES('Group2','State6')

;WITH T as
(
    SELECT
        groups.[Group],
        StateName,
        AVG(Value1) AS Value1,
        AVG(Value2) AS Value2,
        MIN(Value3) AS Value3
    FROM @tblStates states inner join @tblStatesGroups groups on states.StateName = groups.[State]
GROUP BY ROLLUP(groups.[Group],StateName)        
)
SELECT 
    CASE ISNULL(StateName,'') WHEN '' THEN [Group] ELSE StateName END AS StateName,
    Value1,
    Value2,
    Value3      
FROM T  
ORDER BY [Group]

我希望子总计有1个小数点精度,而总计有2个小数点精度。有什么办法吗?

由于

2 个答案:

答案 0 :(得分:1)

唯一的方法是设置精度并将值转换为字符串,以便列类型相同。但你真的需要吗?

SELECT 
    Value1,
    case 
        when StateName is null and [Group] is null then cast(cast(Value1 as decimal(20, 2)) as varchar(30)) 
        when StateName is null and [Group] is not null then cast(cast(Value1 as decimal(20, 1)) as varchar(30)) 
        else cast(cast(Value1 as decimal(20, 2)) as varchar(30)) 
    end 
FROM T  
ORDER BY [Group]

答案 1 :(得分:0)

不幸的是没有。您可以在整列上设置精度。您可以为一列中的不同行指定不同的格式。您可以按列指定格式。在你的情况下,透视你的结果会有所帮助。