0

假设我有一个名为的表'@DeviceSample'和另一个名为'@DevicesActivityDataSample'.

'MAX(DATETIME)'当我在“ DevicesActivityDataSample ”中有重复的行时,我想为每个设备选择前 1 个'@DevicesActivityDataSample',但在我的结果中,我得到了所有重复的行,但我在寻找前一个。另一个问题是,当我想从 100000 行中选择时,由于计算 MAX,需要很长时间才能得到我的结果,这是我的示例代码

DECLARE @DeviceSample TABLE
(
RowID INT IDENTITY(1, 1) PRIMARY KEY CLUSTERED,
ADeviceID INT ,
DeviceName VARCHAR(50) NOT NULL
) 
INSERT @DeviceSample
SELECT 1,'DEVICE 1' UNION ALL
SELECT 2,'DEVICE 2' UNION ALL
SELECT 3,'DEVICE 3'



DECLARE @DevicesActivityDataSample TABLE
(
RowID INT IDENTITY(1, 1) PRIMARY KEY CLUSTERED,
BDeviceID INT,
DeviceDateTime DATETIME,
CMD NVARCHAR(50)
) 

INSERT @DevicesActivityDataSample
SELECT 1, '2013-02-14 19:08:46.000','HHJJ' UNION ALL
SELECT 2, '2013-02-15 03:30:24.000','HHJJ' UNION ALL
SELECT 2, '2013-02-15 03:30:24.000','HHJJ' UNION ALL
SELECT 2, '2013-02-15 03:30:24.000','HHJJ' UNION ALL
SELECT 1, '2013-02-16 03:30:24.000','HHJJ' UNION ALL
SELECT 1, '2013-02-11 03:30:24.000','HHJJ' UNION ALL
SELECT 2, '2013-02-10 03:30:24.000','HHJJ' UNION ALL
SELECT 3, '2013-02-07 04:25:24.000','HHJJ' UNION ALL
SELECT 3, '2013-02-12 23:02:02.000','HHJJ' 



    SELECT  *
    FROM        @DeviceSample
    INNER JOIN  
    @DevicesActivityDataSample 
            ON  ADeviceID = BDeviceID
    WHERE       DeviceDateTime IN (
                    SELECT    MAX(DeviceDateTime) AS MaxDate
                    FROM      @DevicesActivityDataSample                                
                    GROUP BY  BDeviceID
                ) 

GO

以及如何获得 1000000 行或更多行的快速快速结果

4

2 回答 2

5
SELECT DeviceID, MAX(DeviceDateTime)
FROM @DeviceSample
GROUP BY DeviceID;

如果这很慢,请考虑使用 #temp 表而不是 @table 变量(请参阅此处的主要区别),并添加如下索引:

CREATE CLUSTERED INDEX LatestDeviceTime
  ON #DeviceSample (DeviceID, DeviceDateTime DESC);

或者首先不使用表变量或临时表,并在数据来源的基表中添加有用的索引。

于 2013-02-16T05:12:26.023 回答
3

这是每组查询的最大 n。将表变量的定义更改为

DECLARE @DevicesActivityDataSample TABLE (
  RowID          INT IDENTITY(1, 1) PRIMARY KEY CLUSTERED,
  BDeviceID      INT,
  DeviceDateTime DATETIME,
  CMD            NVARCHAR(50),
  UNIQUE (BDeviceID, DeviceDateTime DESC, RowID, CMD) ) 

添加有用的索引。

方法一

SELECT DADS.*
FROM   @DeviceSample DS
       CROSS APPLY (SELECT TOP 1 *
                    FROM   @DevicesActivityDataSample DADS
                    WHERE  DADS.BDeviceID = DS.ADeviceID
                    ORDER  BY DADS.DeviceDateTime DESC) DADS;

方法二

WITH T
     AS (SELECT *,
                ROW_NUMBER() OVER (PARTITION BY BDeviceID 
                                       ORDER BY DeviceDateTime DESC) AS RN
         FROM   @DevicesActivityDataSample)
SELECT *
FROM   T
WHERE  RN = 1 

计划

您也可以考虑使用#temp@Aaron 建议的表格,可能具有以下定义。

CREATE TABLE #DevicesActivityDataSample (
  RowID          INT IDENTITY(1, 1) PRIMARY KEY NONCLUSTERED,
  BDeviceID      INT,
  DeviceDateTime DATETIME,
  CMD            NVARCHAR(50)) 

CREATE CLUSTERED INDEX IX ON #DevicesActivityDataSample(BDeviceID, DeviceDateTime DESC) 

你真的需要RowID吗?

于 2013-02-16T09:36:12.043 回答