我不太确定如何问这个问题,所以我举个例子
我有一个巨大的 table ,类似于这样的东西......
Name Widgets TransDate Location
Abby 2 12/1/2010 Middleton
Abby 13 1/10/2011 Burmingham
Bobby 10 12/12/2011 Easton
Bobby 5 10/10/2011 Weston
.
.
我当前的sql语句是...
SELECT name, widgets, TransDate, Location
FROM MyTable
WHERE TransDate BETWEEN 1/1/2011 and 12/31/2011
给我一张这样的 table ...
Name Widgets TransDate Location
Abby 13 1/10/2011 Burmingham
Bobby 15 12/12/2011 Easton
Bobby 5 10/10/2011 Weston
.
.
如何修改上述 SQL,以同时删除不满足 Widget 配额 X 的人员的记录...假设 X = 16。在这种情况下,Abby 将被删除,因为她的 widget 总数为13 条,鲍比的记录将保留,因为他的总数是 20 条。
提前谢谢您!
最佳答案
如果我理解您的请求,您想要的结果与您已经获得的结果类似,但要过滤那些已达到配额的名称。如果这是正确的,您可以使用 IN()
子查询来查找与 >= 100 个小部件分组的名称。
SELET name, widgets, TransDate, Location FROM MyTable
WHERE
/* IN() subquery for names meeting the quota */
name IN (
SELECT name
FROM tbl
/* If they must have met the quota only during the time window, uncomment below */
/* Otherwise, omit the WHERE clause to find those who have met the quota at any time */
/* WHERE TransDate BETWEEN '1/1/2011' and '12/31/2011' */
GROUP BY name
HAVING SUM(widgets) >= 100
)
AND TransDate BETWEEN '1/1/2011' and '12/31/2011'
关于SQL 仅当总和大于 100 时才选择所有记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8827245/