【发布时间】:2022-01-25 18:33:28
【问题描述】:
我有一个来自我的产品和因素的查询以及要显示的因素项目。
在此查询中,我为用户显示来自因素的报告。
我的查询是:
WITH CTE AS
(
SELECT
ROW_NUMBER() OVER (ORDER BY FactoriTems.datesave ASC) AS rn,
FactoriTems.code, FactoriTems.replacement,
FactoriTems.suggcode, Factors.dateexport,
Productions.descriptions,
FactoriTems.countt, FactoriTems.price,
FactoriTems.countt * FactoriTems.price AS 'total',
Productions.country
FROM
Productions
INNER JOIN
FactoriTems ON Productions.code = FactoriTems.code
INNER JOIN
Factors ON Factors.gid = FactoriTems.gid
WHERE
(FactoriTems.gid = @gid)
)
SELECT *
FROM CTE
ORDER BY rn
这个查询是可以的,但是有一个问题,在Productions表中某些类别有两个或三个产品一个代码,当这个代码在factoritems表中时,我的结果集中显示了两行!
结果是:
| rn | code | dateexport | descriptions | countt | price | total |
|---|---|---|---|---|---|---|
| 1 | aaa | 12/24/2021 | ... | 100 | 2 | 200 |
| 2 | bbb | 12/24/2021 | ... | 200 | 3 | 600 |
| 3 | ccc | 12/24/2021 | ... | 100 | 2 | 200 |
| 4 | ddd | 12/24/2021 | ... | 200 | 3 | 600 |
| 5 | ddd | 12/24/2021 | ... | 100 | 2 | 200 |
| 6 | eee | 12/24/2021 | ... | 200 | 3 | 600 |
现在我如何才能只为'ddd' 产品代码显示一行?
我尝试使用DISTINCT,但出现错误。
我希望输出如下:
| rn | code | dateexport | descriptions | countt | price | total |
|---|---|---|---|---|---|---|
| 1 | aaa | 12/24/2021 | ... | 100 | 2 | 200 |
| 2 | bbb | 12/24/2021 | ... | 200 | 3 | 600 |
| 3 | ccc | 12/24/2021 | ... | 100 | 2 | 200 |
| 4 | ddd | 12/24/2021 | ... | 200 | 3 | 600 |
| 5 | eee | 12/24/2021 | ... | 200 | 3 | 600 |
谢谢
【问题讨论】:
-
在行号中使用产品代码分区,然后为每个产品检索一个值,然后在最终查询中应用 row_number()。
-
@RahulBiswas 我非常感谢您的帮助,但是基于“FactoriTems.datesave”,我的排序对我来说非常重要,当我使用分区时,这种排序就会崩溃。还有一个问题是,当我使用分区时,我的行号崩溃了,但是行号对我来说也很重要。
-
我建议您仔细考虑您的联接,因为在查询中仅使用
DISTINCT或ROW_NUMBER()可能没有帮助。为什么你首先得到重复?哪个联接导致了这种情况,您如何使该联接返回单行?这些是你需要问的问题
标签: sql sql-server inner-join distinct