我有 2 个表,产品和类型,表看起来像这样:
Product
-Id
-Name
-TypeId
Type
-Id
-Name
我希望能够编写一个 SQL Server 查询来输出按类型分组的产品:
+------------+------------+
| Bikes | Product 1 |
| | Product 2 |
| | Product 3 |
| Clothes | Tshirt 1 |
| | Trousers 2 |
| | Hat 3 |
| | Shoes 4 |
| Electrical | Tv |
| | Radio |
| | Laptop |
+------------+------------+
如果我写:
SELECT Type.Name,Product.Name
FROM Product INNER JOIN Type ON Type.Id = Product.TypeId
ORDER By Type.Name
我得到了类似的结果,但是类型值包含在每一列中。
+------------+------------+
| Bikes | Product 1 |
| Bikes | Product 2 |
| Bikes | Product 3 |
| Clothes | Tshirt 1 |
| Clothes | Trousers 2 |
| Clothes | Hat 3 |
| Clothes | Shoes 4 |
| Electrical | Tv |
| Electrical | Radio |
| Electrical | Laptop |
+------------+------------+
使用 SQL Server 有什么办法只能显示第一个类型值吗?
窗口函数在这里可以提供帮助。
顺便说一句,该子句的 MSDN 参考在
OVER
这里:https://msdn.microsoft.com/en-us/library/ms189461.aspx
ROW_NUMBER(事务处理 SQL)
使用这个: