2013-07-15 46 views
5

是否有我如何編輯GROUP BY命令有什麼區別?SQL最快「GROUP BY」腳本

我的代碼:

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

是更快,如果我編輯這樣說:

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

回答

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

+0

要小心,因爲你的例子說,它都是一樣的;但你不應該使用組通過消除重複,這是不正確的,它可能會導致不同的執行計劃,當涉及到的真實的表(因爲索引的使用情況) – jazzytomato

+1

爲了什麼負?請給出意見。 – Devart

+0

@Thomas Haratyk,爲真正的桌子添加執行計劃。 – Devart

3

,最好使用DISTINCT如果你不想彙總數據。否則,有您所提供的兩個查詢之間沒有區別,它會產生相同的查詢計劃

+0

那麼select命令中列的順序與group by by命令中列的順序無關? – nionios

+0

不,它不需要,但它是有道理的:嘗試做一個* GROUP BY *自己很少的數據,一張紙和一支鉛筆:) – jazzytomato