如何连续数数列

How to count consecutively a sequence of number

我需要 SELECT 并计算获得 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

您可以使用 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_NUMBER 的信息:https://docs.microsoft.com/fr-fr/sql/t-sql/functions/row-number-transact-sql?view=sql-server-2017

您需要将 row_number() 函数与 partition byorder by 部分一起使用,如

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

1 开始计算不同的 OrderID

您需要计算不同的订单吗?

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

如果你想要每个订单的此类折扣的数量,那么你想要:

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 中包含其他列来回答这个问题。