【发布时间】:2015-09-04 03:22:32
【问题描述】:
我有以下表格
处置表
Dis_ID | OfferID | RequestID
------------------------------------
34564 | 123 | 9
77456 | 123 | 8
25252 | 124 | 7
46464 | 125 | 10
36464 | 125 | 6
35353 | 125 | 5
请求表
RequestID | AccountNum |
---------------------------
5 | 548543 |
6 | 548543 |
7 | 684567 |
8 | 684567 |
9 | 684567 |
10 | 548543 |
11 | 684567 |
排名表
RankID | OfferId | RequestID | Score
-------------------------------------------
34564 | 123 | 11 | 1
77456 | 124 | 11 | 2
25252 | 125 | 11 | 3
使用上面的数据,我需要一个查询,它的行为如下,给定一个请求编号,查看本示例中排名表中的每条记录,我们有 3 个(123、124 和 125)。返回此联接帐号的处置表中出现次数最少的 OfferId。在此示例中,此帐号的 offerId 123 出现了两次,offerId 124 出现了一次,而此帐号的 offerId 125 根本不出现。所以应该返回 offerId 125。应始终返回存在于 Rank Table 中且在 Disposition 表中出现次数最少的 offerId,除非它们都相同,然后返回 Score 字段中具有最低值的 offerId。例如,如果 Dispostion 表中没有出现任何 offerID,则 offerId 123 将返回,因为它的 Score 值为 1。
结果表看起来像这样
| OfferId | Score | Dis_Occurrences
---------------------------------------------------------------
| 123 | 1 | 2
| 124 | 2 | 1
| 125 | 3 | 0 <--Return this record
这是我目前所拥有的。
SELECT oRank.OfferId, oRank.Rank_Number, count(oRank.OfferId) AS NumDispositions
From Rank oRank
join Request req
on oRank.RequestId = req.RequestId
join Disposition dis
on oRank.OfferId = dis.OfferId
where req.Customer_Account_Number = 684567 and req.RequestId = 11 and oRank.OfferId = dis.OfferId
group by oRank.Rank_Number, oRank.OfferId
order by NumDispositions, oRank.Rank_Number
我不正确的结果表如下所示
| OfferId | Score | Dis_Occurrences
---------------------------------------------------------------
| 123 | 1 | 2
| 124 | 2 | 1
| 125 | 3 | 3
它正在计算 offerId 在 Disposition Table 中出现的总次数
【问题讨论】:
-
Sql server 还是 mysql?
-
@GiorgiNakeuri 我正在使用 MicrosoftSQL。
-
Rank 和 Disposition 表应该如何连接?在您的示例查询中,您通过 RequestID 加入它们,但在您发布的示例数据中,它们之间没有共同的 RequestID。也许您打算改为通过 OfferID 加入?
-
@beercohol 你完全正确我已经更新了我的查询不同的结果但仍然不正确谢谢
标签: sql-server database join sql-server-2012