我有一个关于在sql中编写查询的问题(继续上一个问题:subtract values of two rows and inserting it into a new column (not subsequent rows)):
我想写一个查询来计算用户在当前时间之前赢得比赛的次数,获胜的条件是place = 1;我希望结果出现在新列(win-frequency)中,并且[win-frequency]的值会在新的获胜发生时发生变化。在下图中,我手动计算了win-frequency。
http://www.8pic.ir/images/54691148512772358477.jpg
我写了以下查询,但是我收到了错误:
SELECT [user-name],
submissions,
[date],
place,
recency,
[win-recency],
COUNT( SELECT [date] FROM [top-design1]] td1
WHERE td1.[user-name] = [top-design1].[user-name]
AND place=1
AND [date]< [top-design1].[date]
ORDER BY [date] DESC) as win-frequency
)
FROM [top-design1]
这是sql小提琴: http://sqlfiddle.com/#!3/0ec5f
答案 0 :(得分:2)
您必须修复方括号)
和[
,从相关子查询中删除ORDER BY
,然后转义列名[win-frequency]
。它应该是这样的:
SELECT [user-name],
submissions,
[date],
place,
recency,
[win-recency],
(SELECT COUNT([date])
FROM [top-design1] td1
WHERE td1.[user-name] = [top-design1].[user-name]
AND place = 1
AND [date] < [top-design1].[date]
) as [win-frequency]
FROM [top-design1];