将MySQL join转换为SQL Server语法?

时间:2012-01-05 11:51:14

标签: mysql sql sql-server

在MySQL中我曾经能够做类似的事情:

SELECT Something1.ID, Something2.AverageValue FROM
(SELECT ID, Max(Date) FROM Table GROUP BY ID) Something1
LEFT JOIN
(SELECT ID, AverageValue FROM Table) Something2
ON Something1.ID = Something2.ID

所以我要做的就是给我最新的平均值,每个ID

SQL Server中的语法似乎不同,并且不允许我执行嵌套的SELECT语句?

2 个答案:

答案 0 :(得分:2)

WITH Data AS
(
 SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Date DESC) AS Row_Number,
 ID,
 AverageValue
 FROM Table
)
SELECT * FROM Data WHERE Row_Number = 1

这是您在SQL Server中应该这样做的方式。它使“最后/第一/最大/最小/最大-n-每组”变得简单。

此处的

PARTITION BY关键字等于您的GROUP BY语句,此处的ORDER BY会转换为您在MySQL中使用的MAX聚合函数

使用它可以让你做一些奇特的事情,如:

WITH Data AS
    (
     SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Date DESC) AS Row_Number,
     ID,
     AverageValue
     FROM Table
    )

SELECT Newest.ID, 
Newest.AverageValue, 
(Newest.AverageValue - Next_Newest.AverageValue) AS AverageValue_Change,
Newest.Date
 FROM Data Newest
LEFT OUTER JOIN Data Next_Newest 
 ON Newest.Row_Number+1 = Next_Newest.Row_Number
AND Newest.ID = Next_Newest.ID 

WHERE Newest.Row_Number=1

答案 1 :(得分:1)

是的, 是SQL Server中此查询的问题,因为您的评论有助于查看。

似乎MySQL可以将列表示为表达式而没有别名。这是SQL Server中的“无能为力”。如果SELECT子句中的列是表达式,则必须为其提供别名。因此:

SELECT Something1.ID, Something2.AverageValue FROM
(SELECT ID, Max(Date) AS MaxDate FROM Table GROUP BY ID) Something1
LEFT JOIN
(SELECT ID, AverageValue FROM Table) Something2
ON Something1.ID = Something2.ID

由于您没有在主SELECT中提取MaxDate列,因此您也可以省略它。无论如何,在这种特殊情况下,这似乎是两种产品之间的唯一区别。