相关子查询:“其库存的百分比值占产品线现有库存的百分比”

时间:2016-12-01 23:28:59

标签: sql sql-server

完整问题:报告每种产品,其库存的百分比值,以及其所属产品系列的库存百分比。按产品系列和产品系列中的百分比值降序排列报表。显示两位小数的百分比。

数据库:http://richardtwatson.com/dm6e/images/general/ClassicModels.png

我的尝试......

SELECT P.productCode, ((P.quantityinStock* '100,2') / (SELECT MAX(P.quantityInStock)
FROM Products P)) AS Percent_ 
FROM Products P 
WHERE P.productCode= (SELECT ((COUNT(Q.productLine *100.0))) / (SELECT MAX(Q.productLine))
FROM ProductLines Q
WHERE Q.productLine= P.productCode 
ORDER BY Q.productLine DESC)

我在这些相关的子查询中苦苦挣扎!

2 个答案:

答案 0 :(得分:1)

这是你想要的吗?

;WITH Products(productCode,quantityinStock,productLine) AS (
     SELECT 'Product1',20,'Line1' UNION ALL
     SELECT 'Product2',60,'Line1' UNION ALL
     SELECT 'Product3',30,'Line2' UNION ALL
     SELECT 'Product4',30,'Line2' UNION ALL
     SELECT 'Product5',30,'Line2' 
 )
SELECT P.*,ROUND(P.quantityinStock*1.0/SUM(P.quantityInStock)OVER(PARTITION BY p.productLine)*100,2) AS StockPercent
FROM Products P 
ORDER BY p.productLine desc
productCode quantityinStock productLine StockPercent
----------- --------------- ----------- ---------------------------------------
Product4    30              Line2       33.330000000000
Product5    30              Line2       33.330000000000
Product3    30              Line2       33.330000000000
Product2    60              Line1       75.000000000000
Product1    20              Line1       25.000000000000

答案 1 :(得分:0)

以下是如何获得答案的示例,虽然它不使用相关子查询,但我会将排序和显示保留为两位小数:

Select ...
    p.QuantityInStock * 100.0 / l.LineQtyInStock As [Percent]
  From #product As p
  Join (
    Select Sum(QuantityInStock) As LineQtyInStock,
        ProductLine 
      From #product
      Group By ProductLine) As l On p.ProductLine = l.ProductLine;

当您尝试使用MAX()并返回最高quantityInStock时会遇到一些麻烦,当您实际需要SUM()数量productLine