【发布时间】:2018-06-18 00:11:44
【问题描述】:
我想获取所选供应商的目录以及最后一次购买价格,即 CommandDetails 表中的 Costs 列,如下所示:
Product (idproduct, productName)
Command (idCommand, CommandCode, CommandDate, idSupplier)
CommandDetails(idCommandDetails, idProduct, Qty, idCommand, Costs)
Supplier (idSupplier, SupplierName, SupplierAddress)
SupplierCatalog (idSupplier, idProduct)
我尝试了row_number() Over (Partition by ...) 和其他方法,但我错过了一些东西,我的大脑说得够多了。
期望的结果:
--------------------------------------------------
| SupplierName| ProductName | CommandDate | Costs|
--------------------------------------------------
| SUP1 | P1 | 01/01/2018 | 3,06 |
| SUP1 | P6 | 01/01/2018 | 1,65 |
| SUP1 | P8 | 03/01/2018 | 5,20 |
| SUP1 | P9 | 05/01/2018 | 8,00 |
| SUP1 | P10 | 01/01/2018 | NULL |
--------------------------------------------------
当产品从未被订购时,P10 的成本为零。
我的最后一次尝试:
SELECT
*
FROM
(SELECT
Sct.idsupplier,
SCt.idProduct,
SCD.PurchasePriceCmd Costs,
SCD.Qty,
P.ProCode,
P.ProName,
Row_number() OVER(PARTITION BY Sct.idProduct order by P.ProCode) rn
FROM SupplierCatalog SCt
LEFT JOIN CommandDetails SCD
ON SCD.idProduct = SCat.idProduct
LEFT JOIN Command a
ON a.idCommand = SCD.idCommand
LEFT OUTER JOIN StoreCommand b
ON a.idCommand = b.idCommand
INNER JOIN Product P
ON P.idProduct = SCt.idProduct) t
where Sct.idSupplier = 4 and rn = 1
【问题讨论】:
-
您的查询结果是什么?
-
它什么也不返回,因为当 idsupplier = 4 时,rn 总是不同于 1
-
我在你的架构中没有看到
idStoreCmd -
我刚刚编辑了它的 idCommand,抱歉
标签: c# sql sql-server greatest-n-per-group