我有一个每个位置类型的表(城市,街道,国家等)。
现在我有一个存储过程,需要返回“地点”列表,其中包含“评分最高的评论”。
我有一张临时桌子可以抓住“地点”(可能是任何东西 - 街道,城市等)。
我首先从城市,然后是街道,然后是国家等插入临时表。
我最终获得了一个“地点”临时表,对于每一个我需要获得评分最高的评论。 (最高= BaseScore,例如5.0)
基数:
位置临时表:
DECLARE @ResultSet TABLE
(
[LocationId] INT,
[TopReviewId] INT, -- starts out NULL, need to fill in
[TopReviewContent] NVARCHAR(MAX) -- starts out NULL, need to fill in
)
-- Get the Top Rated Review for each location.
UPDATE ResultSet
SET TopReviewId = TopReview.PostId,
TopReviewContent = TopReview.Content
FROM @ResultSet ResultSet
INNER JOIN
(
SELECT TOP 1 pl.LocationId, p.postid, p.Content
FROM PostLocations pl
INNER JOIN Posts p
ON pl.PostId = p.PostId
INNER JOIN Reviews r
ON p.PostId = r.PostId
INNER JOIN Scores s
ON r.ScoreId = s.ScoreId
INNER JOIN @ResultSet rs
ON pl.LocationId = rs.LocationId
ORDER BY s.BaseScore DESC
) AS TopReview
ON ResultSet.LocationId = TopReview.LocationId
INNER JOIN PostLocations pl
ON ResultSet.LocationId = pl.LocationId
INNER JOIN Posts p
ON pl.PostId = p.PostId
INNER JOIN Reviews r
ON pl.PostId = r.PostId
-- Now return the Results:
SELECT TOP 10
[LocationId],
[TopReviewId],
[TopReviewContent]
FROM @ResultSet
这是输出我目前正在
LocationId TopReviewId TopReviewContent
1 12313 Blah Blah
2 NULL NULL
3 NULL NULL
这是输出我想要
LocationId TopReviewId TopReviewContent
1 12313 Blah Blah
2 44323 Meh meh
3 5345345 Pew pew
答案 0 :(得分:4)
也许这很天真,但你试过了吗?
select c.name, max(price)
from
customer c inner join
product p on p.customerid = c.customerid
group by c.name
如果你想要单一的最佳评论,你可以这样做:
SELECT TOP 1 pl.LocationId, p.postid, p.Content
FROM PostLocations pl
INNER JOIN Posts p
ON pl.PostId = p.PostId
INNER JOIN Reviews r
ON p.PostId = r.PostId
INNER JOIN Scores s
ON r.ScoreId = s.ScoreId
ORDER BY s.BaseScore DESC
如果您希望每个位置获得最佳评价,请执行以下操作:
SELECT pl.LocationId, p.postid, p.Content, max(s.BaseScore)
FROM PostLocations pl
INNER JOIN Posts p
ON pl.PostId = p.PostId
INNER JOIN Reviews r
ON p.PostId = r.PostId
INNER JOIN Scores s
ON r.ScoreId = s.ScoreId
group by p1.locationid, p.postid, p.content
答案 1 :(得分:0)
我对你要做的事情感到有点困惑。但要获得客户列表及其最高订单ID,您不能这样做吗?
select customers.name, orders.orderid
from customers join orders on customers.customerid = orders.customerid
group by customers.customerid
having max(orders.price);