SQL最快的'GROUP BY'脚本

时间:2013-07-15 09:15:48

标签: sql sql-server sql-server-2005 group-by

我编辑GROUP BY命令的方式有什么不同吗?

我的代码:

SELECT Number, Id 
    FROM Table
    WHERE(....)
    GROUP BY Id, Number

如果我像这样编辑它会更快:

 SELECT Number, Id 
    FROM Table
    WHERE(....)
    GROUP BY Number , Id

2 个答案:

答案 0 :(得分:3)

如果您不想聚合数据,最好使用DISTINCT。否则,您提供的两个查询之间没有区别,它将生成相同的查询计划

答案 1 :(得分:2)

这个例子是平等的。

<强> DDL:

CREATE TABLE dbo.[WorkOut]
(
    [WorkOutID] [bigint] IDENTITY(1,1) NOT NULL PRIMARY KEY,
    [TimeSheetDate] [datetime] NOT NULL,
    [DateOut] [datetime] NOT NULL,
    [EmployeeID] [int] NOT NULL,
    [IsMainWorkPlace] [bit] NOT NULL,
    [DepartmentUID] [uniqueidentifier] NOT NULL,
    [WorkPlaceUID] [uniqueidentifier] NULL,
    [TeamUID] [uniqueidentifier] NULL,
    [WorkShiftCD] [nvarchar](10) NULL,
    [WorkHours] [real] NULL,
    [AbsenceCode] [varchar](25) NULL,
    [PaymentType] [char](2) NULL,
    [CategoryID] [int] NULL
)

<强>查询:

SELECT wo.WorkOutID, wo.TimeSheetDate 
FROM dbo.WorkOut wo
GROUP BY wo.WorkOutID, wo.TimeSheetDate

SELECT DISTINCT wo.WorkOutID, wo.TimeSheetDate 
FROM dbo.WorkOut wo

SELECT wo.DateOut, wo.EmployeeID
FROM dbo.WorkOut wo
GROUP BY wo.DateOut, wo.EmployeeID

SELECT DISTINCT wo.DateOut, wo.EmployeeID 
FROM dbo.WorkOut wo

执行计划:

pp