如何在具有数百万条记录的 table 上使用 MAX

How to use MAX on a table with millions of records

我有一个 table,其中包含与交易相关的所有信息,它具有进行销售的设备 ID 以及交易编号(此 table 有数百万行)。我在临时 table 上有一些 DeviceID 的列表,我正在加入事务 table 以获得最大事务编号,但它需要很长时间才能显示结果。有没有更好的方法来编写 sql 语法以在更短的时间内获得结果?也许对相同的事务 table 进行子查询以获得 MAX 值,任何想法将不胜感激。我当前的代码如下:

select a.DeviceID,
MAX(tq.Transaction_number)
from Datawarehouse.DBO.Transactions tq with (nolock)
/*The #Temp1 table contains the Device IDs we want to get the MAX transaction number ,
the total amount of Devices are between 1 and 1000 */
inner join #Temp1 a on a.DeviceID = tq.DeviceID
--We only want the MAX transaction number for sales ( Not Refunds)
where tq.Transaction_type = 'SALES'

有时这样效果更好:

select t.*,
       (select max(tq.Transaction_number)
        from Datawarehouse.DBO.Transactions tq
        where t.DeviceID = tq.DeviceID and tq.Transaction_type = 'SALES'
       )
from #temp1 t;

特别是,您想要 Transactions(DeviceID, Transaction_type, Transaction_number desc) 上的复合索引。

我认为适当的索引会有所帮助。看看Example-Fiddle

查询:

Select
    d.device_id,
    MAX( t.transaction_id ) transaction_id
From
    devices d
JOIN
    transactions t
    ON t.device_id = d.device_id
    # AND transaction_types = ...
GROUP BY
    d.device_id;

您可以使用 apply :

select t.DeviceID, tt.Transaction_no
from #temp1 t cross apply ( 
     select max(tr.Transaction_number) Transaction_no
     from Datawarehouse.DBO.Transactions tr
     where t.DeviceID = tr.DeviceID and 
           tr.Transaction_type = 'SALES'
) tt;

但是,如果您在 (DeviceID, Transaction_type &Transaction_number) 并且不要忘记在查询之前 SET NOCOUNT 尤其是在使用 SSMS 时。