如何为该百分比查询编写sql查询?

时间:2019-04-08 19:17:23

标签: sql sql-server

我想计算数据库中的百分比。我的英语不好,所以我要给我看两张我想做什么的照片。

enter image description here

enter image description here

3 个答案:

答案 0 :(得分:0)

首先获取总费用,在第二个查询中,我们根据“名称”计算费用和百分比。

DECLARE @tbl TABLE
(
    id int IDENTITY(1,1),
    Name varchar(100),
    Cost int
)

INSERT INTO @tbl VALUES('Kelly',100)
INSERT INTO @tbl VALUES('Tom',50)
INSERT INTO @tbl VALUES('Kelly',30)
INSERT INTO @tbl VALUES('Mike',40)
INSERT INTO @tbl VALUES('Peter',30)
INSERT INTO @tbl VALUES('Peter',10)

DECLARE @total int

SELECT @total = sum(Cost) FROM @tbl t

SELECT @total

SELECT Name, Cost = SUM(Cost), Percentage = Cast((SUM(Cost)/ (@total * 1.00)) *100.00 AS decimal(18,2)) FROM @tbl t
GROUP BY t.Name

输出:

Name Cost Percentage Kelly 130 50.00 Mike 40 15.38 Peter 40 15.38 Tom 50 19.23

答案 1 :(得分:0)

SELECT
    name,
    SUM(Cost) Cost,
    (SELECT sum(Cost) FROM data) TotCost,
    SUM(Cost) / (SELECT SUM(Cost) FROM data) Perc
FROM data
GROUP BY name

答案 2 :(得分:0)

您可以尝试以下操作:

输入:

CREATE TABLE #Table (
  [Name] varchar(50),
  [Cost] int
)
INSERT INTO #Table
   ([Name], [Cost])
VALUES
   ('Kelly', 100),
   ('Tom', 50),
   ('Kelly', 30),
   ('Mike', 40),
   ('Peter', 30),
   ('Peter', 10)

方法,仅使用计算:

SELECT 
   [Name], 
   CONVERT(numeric(10, 2), SUM([Cost])* 100.0 / (SELECT SUM([Cost]) FROM #Table)) AS Percentage
FROM #Table
GROUP BY [Name]
ORDER BY CONVERT(numeric(10, 2), SUM([Cost])* 100.0 / (SELECT SUM([Cost]) FROM #Table))

输出:

Name    Percentage
Kelly   50.00
Tom     19.23
Mike    15.38
Peter   15.38

通过此计算,由于roundingimplicit type conversion,百分比的总和并不总是100。下一条语句解决了这个问题:

;WITH CalculatedCTE AS (
    SELECT 
        [Name], 
        SUM([Cost])* 100.0 / (SELECT SUM([Cost]) FROM #Table) AS Percentage,
        ROW_NUMBER() OVER (ORDER BY [Name] DESC) AS Rn
    FROM #Table
    GROUP BY [Name]
)
SELECT 
    [Name],
    CASE 
        WHEN Rn = 1 THEN CONVERT(int, [Percentage]) + (100 - SUM(CONVERT(int, [Percentage])) OVER ())
        ELSE CONVERT(int, [Percentage]) 
    END AS [Percentage]
FROM CalculatedCTE
ORDER BY [Name]

输出:

Name    Percentage
Kelly   50
Mike    15
Peter   15
Tom     20