SQL:减小结果集的大小

时间:2015-07-01 08:56:43

标签: sql sql-server

SELECT p.Distributor, SUM(r.SalesVolume) as Sales, 
((Cast(SUM(r.SalesVolume) as decimal(14, 4)) / (SELECT SUM(r.SalesVolume) FROM RawData r)) * 100) as MarketSharesVolume
FROM RawData r
INNER JOIN Product p
ON r.ProductId = p.ProductId
WHERE p.Distributor in ('TF1','WARNER')
GROUP BY p.Distributor;

上述查询的结果是:

Distributor    Sales    MarketSharesVolume
  WARNER      2836192   58.131470300744400
  TF1         268668    5.506702600797200

基本上我希望MarketSharesVolume的值为58.1 我尝试更改精度decimal(14, 4),但每个其他组合都给我一个Arithmetic Overflow error。 有没有办法可以截断列?

3 个答案:

答案 0 :(得分:1)

documentation。使用ROUND()获取正确的值,使用CONVERT()删除尾随零。您可以将此应用于您的查询。

DECLARE @Val DECIMAL(28, 18) = 58.131470300744400
SELECT CONVERT(decimal(28, 1), ROUND(@Val, 1))

答案 1 :(得分:1)

您可以转换列的数据类型:

       SELECT p.Distributor, SUM(r.SalesVolume) as Sales, 
    CAST( (Cast(SUM(r.SalesVolume) as decimal(14, 4)) / (SELECT SUM(r.SalesVolume) FROM RawData r)) * 100 
   as decimal(20,1)) as MarketSharesVolume
    FROM RawData r
    INNER JOIN Product p
    ON r.ProductId = p.ProductId
    WHERE p.Distributor in ('TF1','WARNER')
    GROUP BY p.Distributor;

答案 2 :(得分:1)

如果您使用的是SQL Server 2012或更高版本,您甚至可以像这样使用FORMAT

DECLARE @v DECIMAL(18,9) = 234.234342345

SELECT @v,FORMAT(@v,'.00'),CAST(@v as DECIMAL(18,2))