有2个表:users
和offers
。
我需要为每个用户提取3个优惠。
我写了这个命令行:
SELECT TOP 10
sellerID,
Country,
(SELECT TOP 3 ItemID
FROM Items i
JOIN Sellers s ON s.sellerID = i.UserID
ORDER BY CreatedDate)
FROM
Sellers
ORDER BY
Country desc
不确定是否真的会返回我正在寻找的内容,但我收到此错误:
子查询返回的值超过1 当子查询遵循=,!=,<,< =,>时,不允许这样做。 >,> =或当子查询用作表达式时。
可以建议解决方案或解决方法吗?
答案 0 :(得分:1)
CROSS APPLY
就是您所需要的。请参阅查询示例:
SELECT TOP (10) S.SellerID, S.Country, I.ItemID
FROM dbo.Sellers AS S
CROSS APPLY (
SELECT TOP (3) I.ItemID
FROM dbo.Items AS I
WHERE S.SellerID = I.UserID
ORDER BY I.CreatedDate
) AS I
ORDER BY S.Country DESC;
此查询会返回TOP (10)
个结果。如果您想为每个用户获取TOP (10)
个用户和3个项目(这意味着最多30个记录),请改用此查询:
SELECT S.SellerID, S.Country, I.ItemID
FROM (
SELECT TOP (10) S.SellerID, S.Country
FROM dbo.Sellers AS S
ORDER BY S.Country DESC
) AS S
CROSS APPLY (
SELECT TOP (3) I.ItemID
FROM dbo.Items AS I
WHERE S.SellerID = I.UserID
ORDER BY I.CreatedDate
) AS I;
其中一个用途正是你所要求的。返回TOP (n)
子项。更多真实的例子可以在这里找到:Real life example, when to use OUTER / CROSS APPLY in SQL
答案 1 :(得分:0)
您在select子句中有子查询。它必须在那里返回1行。尝试加入它 -
SELECT
TOP 10 sellerID,
Country, items.ItemID
from Sellers
left join
(
SELECT TOP 3 UserID, ItemID
from Items i
join Sellers s
on s.sellerID=i.UserID
order by CreatedDate
) items
on sellers.UserID = items.UserID
order by Country desc
答案 2 :(得分:0)
当前的问题是,您已要求select
输出每行包含sellerId
,Country
和三个值{{1}的值的行}}
子查询也与外部查询无关,即您对ItemID
表有第二次引用,但没有做任何事情来匹配外部查询的值。
假设您确实想要最多10个国家/地区的前3个项目,那么这应该是关闭的:
Sellers
答案 3 :(得分:0)
此查询适合您:
SELECT TOP 10 sellerID, Country, items.ItemID
from Sellers
left join Items On Items.UserID = Sellers.sellerID
And Items.ItemID in ( Select Top 3 I_1.ItemID From Items As I_1
Where I_1.UserID = Sellers.sellerID
Order by CreatedDate )
ORDER BY Country desc