google_ad_clIEnt = "pub-6430022987645146";google_ad_width = 120;google_ad_height = 600;google_ad_format = "120x600_as";google_cpa_choice = "CAEaCDMJ9_YamEPDUDRQHVASUAVQB1AvUANQDFBHUEM";google_color_border = "336699";google_color_bg = "FFFFFF";google_color_link = "0000FF";google_color_text = "000000";google_color_url = "008000";
google_ad_client = "pub-6430022987645146";google_ad_width = 468;google_ad_height = 60;google_ad_format = "468x60_as";google_ad_type = "text_image";google_ad_channel = "";google_color_border = "336699";google_color_bg = "FFFFFF";google_color_link = "0000FF";google_color_text = "000000";google_color_url = "008000"; google_ad_clIEnt = "pub-6430022987645146";google_ad_width = 160;google_ad_height = 600;google_ad_format = "160x600_as";google_ad_type = "text_image";google_ad_channel = "";google_color_border = "6699CC";google_color_bg = "003366";google_color_link = "FFFFFF";google_color_text = "AECCEB";google_color_url = "AECCEB";google_ui_features = "rc:0";
“每個Y的最新X”是一個經典的SQL問題,工作中經常碰到。當然不是“按Y分組求最新的X值”那麼簡單,要求最新X的那條記錄或主鍵ID。用一條SQL語句可以簡單的解決此問題。
生成實例表和數據:
--創建表
CREATE TABLE dbo.Tab
(
ID int NOT NULL IDENTITY (1, 1),
Y varchar(20) NOT NULL,
X datetime NOT NULL
)
GO
--插入數據
INSERT INTO Tab(Y, X) values('BBB', '2007-10-23 11:11:11')
INSERT INTO Tab(Y, X) values('BBB', '2007-10-23 11:11:11')
INSERT INTO Tab(Y, X) values('BBB', '2007-10-23 10:10:10')
INSERT INTO Tab(Y, X) values('AAA', '2007-10-23 12:12:12')
INSERT INTO Tab(Y, X) values('AAA', '2007-10-23 10:10:10')
INSERT INTO Tab(Y, X) values('AAA', '2007-10-23 11:11:11')
GO
解決“每個Y的最新X”經典SQL問題:
--一條SQL語句實現
SELECT ID, Y, X
FROM Tab T
WHERE (NOT EXISTS
(SELECT 1
FROM Tab T2
WHERE (T2.Y = T.Y) AND (T2.X > T.X OR
T2.X = T.X AND T2.ID > T.ID)))
在Y列在建立索引,可以大大優化查詢速度。