如何选择最后25%的数据集

时间:2015-05-04 10:35:00

标签: sql sql-server

给我们的问题是'显示数量在底部四分位数中的所有不同订单。

我尝试了以下

USE [Northwind]
GO

DECLARE @maxValue int
SELECT @maxValue = MAX(Quantity) FROM [Order Details]

SELECT OrderID, ProductID, (Quantity / @maxValue) AS 'tot'
FROM [Order Details] AS od
WHERE 'tot' <= 0.25
ORDER BY ProductID
GO

输出应该如下所示

output should look like this

我的剧本中出错了什么?

4 个答案:

答案 0 :(得分:1)

您可以先将其转换为DECIMAL,然后再进行匹配 这样的东西。((Quantity *1.0) / @maxValue)

DECLARE @maxValue DECIMAL(18,2)
SELECT @maxValue = MAX(Quantity) FROM [Order Details]
SELECT OrderID, ProductID, ((Quantity *1.0) / @maxValue) AS 'tot'
FROM [Order Details] AS od
WHERE ((Quantity *1.0) / @maxValue) <= 0.25
ORDER BY ProductID

您可以选择使用此WHERE

之类的WHERE Quantity <= (@maxValue * 0.25 )子句

答案 1 :(得分:1)

您是否尝试过(Quantity / @maxValue)<=0.25而不是&#39; tot&#39;?

答案 2 :(得分:0)

我会使用WINDOWED functions来实现这一目标。您不必两次查询[订单明细]表。请尝试:

SELECT *
FROM (
    SELECT od.OrderID, od.ProductID, ((od.Quantity * 1.00) / MAX(od.Quantity) OVER())) AS tot
    FROM [Order Details] AS od
    ) AS T
WHERE T.tot <= 0.25
ORDER BY T.ProductID;

但是你的描述说,你正在寻找底部四分位数,因此让我认为NTILE()对你来说是更好的方法:

SELECT *
FROM (
    SELECT od.OrderID, od.ProductID, NTILE(4) OVER (ORDER BY od.Quantity) AS Quartile
    FROM [Order Details] AS od
    ) AS T
WHERE T.Quartile = 1
ORDER BY T.ProductID;

答案 3 :(得分:0)

我找到了解决问题的方法。

USE Northwind
GO

SELECT DISTINCT a.OrderID, a.ProductID
FROM [Order Details] as a
WHERE Quantity <= (SELECT AVG(Quantity * 0.25
             FROM [Order Details]
             WHERE a.ProductID = ProductID)
GO