[英]How to include an 'order' or 'index' column in a SELECT query?
I'm using Access SQL . 我正在使用Access SQL 。 I want to add a column
to my query that acts like a row number
for each record, but because I'm using an aggregate function, the results have not ids themselves. 我想在我的查询中添加一个column
,其行为类似于每个记录的row number
,但由于我使用的是聚合函数,因此结果本身并不是id。 Is there any function that generate some row numbers for this ? 是否有任何函数可以为此生成一些行号? even like Autonumber or index or just the order . 甚至像Autonumber或索引或只是订单 。 So my dummy SQL syntax is like: 所以我的虚拟SQL语法如下:
SELECT [wanted autonumber column], product,Sum(amount) FROM Invoices_Items GROUP BY product
I guessed maybe it would be good if I create a temporary table for this query with an autonumber column but I don't know how to that. 我猜想如果我用自动编号列为这个查询创建一个临时表可能会很好,但我不知道如何做到这一点。
If you save the GROUP BY
SQL as a named query in Access, you can use that as the data source for another SELECT
statement which uses a correlated subquery to generate a row number. 如果将GROUP BY
SQL保存为Access中的命名查询,则可以将其用作另一个SELECT
语句的数据源,该语句使用相关子查询生成行号。
So with this SQL saved as qryInvoices_Items1 ... 所以这个SQL保存为qryInvoices_Items1 ...
SELECT i.product, Sum(i.amount) AS SumOfamount
FROM Invoices_Items AS i
GROUP BY i.product;
This query will add a dynamic row number --- the row number for a given product can be different from one run to the next if the underlying Invoices_Items
data changes. 此查询将添加动态行号---如果基础Invoices_Items
数据发生更改,则给定产品的行号可能会因一次运行而异。
SELECT
(
SELECT Count(*)
FROM qryInvoices_Items1 AS q2
WHERE q2.product <= q1.product
) AS row_number,
q1.product,
q1.SumOfamount
FROM qryInvoices_Items1 AS q1;
I tested that SQL in Access 2007, and it returns the result I think you're looking for. 我在Access 2007中测试了SQL,它返回了我认为你正在寻找的结果。 However, if I'm wrong about that point, please include Invoices_Items
sample data in your question (as text, not a screen capture image) and show us the output you want based on that sample data. 但是,如果我对此有误,请在您的问题中包含Invoices_Items
样本数据(作为文本,而不是屏幕截图),并根据该样本数据向我们显示您想要的输出。
Note a correlated subquery requires the db engine run that subquery separately for each row of the parent query's result set. 请注意,相关子查询要求db引擎分别为父查询的结果集的每一行运行该子查询。 That would be a big performance challenge with a huge data set. 这对于庞大的数据集来说将是一个巨大的性能挑战。 However, if your data set is small enough, the perform impact could be tolerable, or maybe not even noticeable. 但是,如果您的数据集足够小,则可以容忍执行影响,甚至可能无法察觉。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.