2012-08-23 72 views
2

如何將此MySQL查詢放入SQL Server等效項中?將IF從子句從MySQL移植到SQL Server 2005中

SELECT User.id, User.first, User.last, 
IF (User.first = q1 OR User.first = q2, 1, 0) + 
IF (User.last = q1 OR User.last = q2, 1, 0) as points 
FROM users as User 
ORDER BY points DESC 

回答

4

相當於IF在SQL Server是CASE expression。 (或IIF in SQL Server 2012。)我也刪除了在這種情況下似乎毫無意義的別名。

SELECT id, first, last, 
    CASE WHEN first IN (q1,q2) THEN 1 ELSE 0 END 
    + CASE WHEN last IN (q1,q2) THEN 1 ELSE 0 END AS points 
FROM dbo.users 
ORDER BY points DESC;