划分两个SQL查询结果

时间:2016-10-11 19:06:17

标签: sql sql-server select

我只是想学习如何从列中获取值,在这种情况下,JJ在产品a上花费了多少,并将其除以产品A总销售额的总和并将其转换为百分比。 / p>

我的SQL理解现在处于相当低的水平,因此响应越简单越好。

SELECT 
    JJ / Result * 100 AS percentage
FROM
    (SELECT 
         ([Product A] AS JJ
     FROM [Test].[dbo].[TableA]
     WHERE [Customer Name] = 'JJ' 


    SELECT SUM([Product A]) AS Result 
    FROM [Test].[dbo].[TableA]   
)
--JJ/Result * 100 = ProdAPercentSales)

1 个答案:

答案 0 :(得分:2)

您可以使用case表达式查找JJ的购买,并将其总和除以总和:

SELECT SUM(CASE [Customer name] WHEN 'JJ' THEN [Product A] ELSE 0 END) /
       SUM([Product A]) * 100 AS [Percentage]
FROM   [Test].[dbo].[TableA]