抱歉坚持这个查询,因为我在order by子句中有数据它告诉我我必须放入聚合或group by子句? (即使我不需要那个总值?)。
表UserData(userID,sales,credits,dateCreated)
我的查询必须返回最后10个结果:
选择TOP 10 COUNT(*)作为totalDays,SUM(销售额),SUM(点数) 来自UserData WHERE userID = @userID ORDER BY dateCreated DESC
我有总天数,因为它可能不会返回我要求的天数(在这种情况下它是10,但可以在以后更改)。
答案 0 :(得分:1)
这将为您提供过去10天的总数:
SELECT
COUNT(*) as totalDays, SUM(sales), SUM(credits)
FROM
UserData
WHERE
userID = @userID
AND DateCreated > GETDATE() - 10
过去10次销售
SELECT COUNT(*) as totalDays, SUM(sales), SUM(credits)
FROM
(SELECT TOP 10 sales, credits
FROM UserData
WHERE userID = @userID
ORDER BY dateCreated DESC) X
答案 1 :(得分:1)
对于仅在结果中返回单行的查询使用top
或order by
没有意义。首先,您必须使查询返回多行才能使用它们。
这将简单地汇总所有销售并返回一行,因此您必须先对其执行某些操作:
select count(*) as totalDays, sum(sales), sum(credits)
from UserData
where userID = @userID
如果您想进行最后十次销售并总结,您需要一个首先隔离十个销售额的子查询,然后您可以将它们聚合在一起:
select count(*) as totalDays, sum(sales), sum(credits)
from (
select top 10 sales, credits
from UserData
where userID = @userID
order by dateCreated desc
) LastData
如果您想在每天总结过去十天的回报,您需要在该日期进行分组:
select top 10 count(*) as totalDays, sum(sales), sum(credits)
from UserData
where userID = @userID
group by dateCreated
order by dateCreated desc
答案 2 :(得分:0)
这是因为*(ALL)字段而发生的。 由于你聚合了你应该选择另一个字段来计算,任何字段都会在你的情况下做,这将使你的查询像这样:
选择TOP 10 COUNT(USERID)作为TOTALDAYS,SUM(SALES),SUM(CREDITS) 来自USERDATA WHERE userid = @userid GROUP BY datecreated ORDER BY datecreated DESC
即使在SELECT子句中没有使用datecreated,它仍然需要在GROUP BY部分。
希望这有帮助。