我正在使用SQL Server 2008,我有一个SALES_ORDER表。 表格的每一行都是一种材料。许多行(材质)可以属于同一个ORDER。我想在两种情况下选择许多订单的材料:
例如,假设我们有
ValueError: modifications to a property of a datetimelike object are not supported. Change values on the original.
和ROW_MAX = 7
查询必须返回
知道怎么用SQL脚本吗?
答案 0 :(得分:1)
我认为这比那更棘手。我猜以下代码回答了必要条件:
任何其他订单组合,因此总数或所选行数不超过7
在你交叉申请之前,你几乎没有什么工作要做。
首先我们创建一个数据样本,其中order1 + order2大于7(这样我们就可以测试并且不会停止查看order2):
-- A sample table in which order1 + order 2 count is bigger than 7
IF OBJECT_ID('tempdb..#sample') is not null
DROP TABLE #sample
CREATE TABLE #sample (
OrderID INT,
OrderDesc VARCHAR(50)
)
INSERT INTO #sample VALUES
(1, 'Order 1 customer 1'),
(1, 'Order 2 customer 1'),
(1, 'Order 3 customer 1'),
(1, 'Order 4 customer 1'),
(2, 'Order 1 customer 2'),
(2, 'Order 2 customer 2'),
(2, 'Order 3 customer 2'),
(2, 'Order 4 customer 2'),
(2, 'Order 5 customer 2'),
(3, 'Order 1 customer 3'),
(3, 'Order 2 customer 3'),
(4, 'Order 1 customer 4')
然后我们计算每个订单的行数:
-- Counting rows for each order
IF OBJECT_ID('tempdb..#samplecount') is not null
DROP TABLE #samplecount
SELECT OrderID, COUNT(*) as OrderCount
INTO #samplecount
FROM #sample
GROUP BY OrderID
我们按照这个数量订购订单:
--Numbering each row
IF OBJECT_ID('tempdb..#samplecountordered') is not null
DROP TABLE #samplecountordered
SELECT *, ROW_NUMBER() OVER(ORDER BY OrderCount) AS OrderNumber
INTO #samplecountordered
from #samplecount
之后我们可以在有组织的存储库上使用交叉申请:
select sa.*
from #samplecountordered so cross apply
(select SUM(OrderCount) as running_count
from #samplecountordered so2
where so2.OrderNumber <= so.OrderNumber
) so2
INNER JOIN #sample sa
ON sa.OrderID = so.orderID
where running_count <= 7;
此解决方案需要进一步测试,但我想这是精神。 我使用临时表,以便在构造方面更容易理解。
抱歉,我使用的是客户而不是材料。
答案 1 :(得分:0)
您正在寻找累计金额。在SQL Server 2008中,您可以使用apply
执行此操作:
select so.*
from sales_order so cross apply
(select count(*) as running_count
from sales_order so2
where so2.order_id <= so.order_id
) so2
where running_count <= 7;