以往寫 T-SQL 有用到 Derived Tables 時,都是用下面這個例子的寫法為主,Alias 會寫在 ColumnName 後面,比較直覺
SELECT orderyear, COUNT(DISTINCT custid) AS cust_count FROM ( SELECT YEAR(orderdate) AS orderyear, -- Alias 寫在 ColumnName 後面 custid FROM Sales.Orders ) AS derived_year GROUP BY orderyear;MVA 課程中介紹的寫法,寫在整個 Derived Tables ColumnName 中
SELECT orderyear, COUNT(DISTINCT custid) AS cust_count FROM ( SELECT YEAR(orderdate), -- 不在欄位後面取 Alias custid FROM Sales.Orders ) AS derived_year(orderyear, custid) -- 寫在整個 Derived Tables ColumnName 中 GROUP BY orderyear;原以為是 SQL Server 2012 的新語法 EXEC WITH Result Set 相關,但實際在 2005 上測試也是 OK 的
- 參考資料
- Querying with Transact-SQL 7 - Using Table Expressions
沒有留言:
張貼留言