如何连续计算数字序列

时间:2019-04-09 09:25:40

标签: sql sql-server northwind

我需要选择并计算已获得10%折扣的OrderID的数量。

我尝试使用COUNT函数,但是它仅计算一个唯一实体的出现,而不是每个OrderID的计数。

USE Northwind
GO

SELECT a.OrderID, COUNT(a.OrderID) as 'SeqNo', b.ProductName, a.UnitPrice, a.Quantity, a.UnitPrice*a.Quantity as Amount, a.Discount
FROM [Order Details] as a
INNER JOIN [Products] as b
ON a.ProductID = b.ProductID
GROUP BY a.OrderID, b.ProductName, a.UnitPrice, a.Quantity, a.Discount
HAVING a.Discount = 0.1

我实际上希望'SeqNo'来计数OrderID,但是所有的都是1。

  OrderID SeqNo       ProductName      UnitPrice Quantity Amount Discount
1  10288  | 1  | Tourtiere             | 5.9    |  10 |   59.00  | 0.1
2  10288  | 2  | Scottish Longbreads   | 10     |  3  |   30.00  | 0.1
3  10291  | 1  | Konbu                 | 4.8    |  20 |   96.00  | 0.1
3  10291  | 2  | Gula Malacca          | 15.5   |  24 |   372.00 | 0.1
3  10291  | 3  | Mankimup Dried Apples | 42.4   |  2  |   84.8   | 0.1

4 个答案:

答案 0 :(得分:0)

您可以使用ROW_NUMBER代替COUNT

USE Northwind
GO

SELECT a.OrderID
, ROW_NUMBER() OVER(ORDER BY a.OrderID ASC) AS 'SeqNo'
, b.ProductName
, a.UnitPrice
, a.Quantity
, a.UnitPrice*a.Quantity as Amount
, a.Discount
FROM [Order Details] as a
INNER JOIN [Products] as b
ON a.ProductID = b.ProductID
GROUP BY a.OrderID, b.ProductName, a.UnitPrice, a.Quantity, a.Discount
HAVING a.Discount = 0.1

详细了解ROW_NUMBERhttps://docs.microsoft.com/fr-fr/sql/t-sql/functions/row-number-transact-sql?view=sql-server-2017

答案 1 :(得分:0)

您需要将row_number()partition by部分的order by函数用作

row_number() over (partition by OrderID  order by OrderID ) as SeqNo

1开始,对不同的OrderID进行每次计数

答案 2 :(得分:0)

您需要计算不同订单吗?

select Count(distinct OrderID) from [Order Details] where Discount=0.1

答案 3 :(得分:0)

如果您想获得每个订单的此类折扣数量,则需要:

SELECT od.OrderID, COUNT(*) as num_discounts
FROM [Order Details] od
WHERE od.Discount = 0.1
GROUP BY od.OrderID;

如果您希望在任何订单行上都打折的订单数量:

SELECT COUNT(DISTINCT od.OrderID)
FROM [Order Details] od
WHERE od.Discount = 0.1;

我不确定您为什么在SELECT中包括其他列来回答此问题。