sql - Select with Row_Number using join. Fetching last three customers with their respective addresses
问题描述
I want to fetch the last three customers from my database with their respective addresses without using TOP
statement because using that way should be wrong. For that purpose I'm using the ROW_NUMBER()
function.
This is my query:
SELECT *
FROM (
SELECT ROW_NUMBER() OVER (ORDER BY c.customerId DESC) AS lastCustomers, *
FROM Customer c JOIN Address a ON c.customerId = a.customerId
)
WHERE lastCustomers <= 3
When I'm executing this query I've got the following error:
Incorrect syntax near the keyword 'WHERE'.
Can anyone solve this syntax error for this query?
解决方案
SQL Server -- as with many other databases -- requires table aliases for subqueries:
SELECT ca.*
FROM (SELECT ROW_NUMBER() OVER (ORDER BY c.customerId DESC) AS lastCustomers,
c.*, a.* -- might get an error for repeated columns
FROM Customer c JOIN
Address a
ON c.customerId = a.customerId
) ca
WHERE lastCustomers <= 3;
This will then generate an error because the subquery has repeated columns.
Generally, this is easier to write as:
SELECT TOP (3) ROW_NUMBER() OVER (ORDER BY c.customerId DESC) AS lastCustomers,
c.*, a.* -- might get an error for repeated columns
FROM Customer c JOIN
Address a
ON c.customerId = a.customerId
ORDER BY c.customerId DESC;
推荐阅读
- format - MDX - 范围内的 StrToMember
- wordpress - Wordpress Algolia 插件,仅将所有帖子索引到 searchable_posts 索引中,而不是启用的?
- node.js - 如何在 AWS Lambda 中保留信息直到下一次执行
- python - 迭代深度嵌套的熊猫 json 对象?
- c# - Wpf从样式中绑定TextBlock的文本属性
- firebase - Firebase 用户对象在 Localhost 上为空
- cesium - 当我在浏览器中加载 cesium.js 时出现 Cesium-terrain-builder-docker 错误
- c++ - C++ Qt4:使用 QObject 实现添加插槽
- matlab - MATLAB中符号变量和普通变量的区别?
- c# - PDF 提取坐标并创建嵌套 XML 文件