简体   繁体   English

SQL仅在总和大于100时才选择所有记录

[英]SQL select all records only if the sum is greater than 100

I'm not exactly sure how to ask this so I'll give an example 我不确定如何问这个,所以我举个例子

I have a huge table that resembles something like this... 我有一张类似这样的巨大桌子......

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
.
.

And my current sql statement is... 我目前的sql语句是......

SELECT name, widgets, TransDate, Location 
FROM MyTable
WHERE TransDate BETWEEN 1/1/2011 and 12/31/2011

to give me a table like this... 给我一张这样的桌子......

Name Widgets TransDate  Location
Abby  13     1/10/2011  Burmingham
Bobby 15     12/12/2011 Easton
Bobby 5      10/10/2011 Weston
.
.

How do I modify the above SQL to also get rid of the records of people who do not meet a Widget quota X... say X = 16. In this case, Abby would be dropped because her total # of widgets is 13 and Bobby's records would stay because his total is 20. 我如何修改上面的SQL,以便除去那些不符合Widget配额X的人的记录...说X = 16.在这种情况下,Abby会被删除,因为她的小部件总数是13和Bobby的记录将保留,因为他的总数是20。

Thank you in advance! 先感谢您!

If I understand your request, you want similar results to what you've already got, but filtering for those names who have met the quota. 如果我理解您的请求,您希望获得与您已经获得的结果类似的结果,但要过滤那些符合配额的名称。 If that is correct, you can use an IN() subquery to find names grouped with >= 100 widgets. 如果这是正确的,您可以使用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'

for sql server it could be done like this 对于sql server,它可以像这样完成

SELECT m.name, m.widgets, m.TransDate, m.Location 
FROM MyTable m
JOIN(SELECT name, SUM(widgets) 
            FROM  MyTable 
            WHERE TransDate BETWEEN '1/1/2011' and '12/31/2011'
            GROUP BY NAME 
            HAVING SUM(widgets) >= 16) x
ON x.NAME = m.NAME
WHERE m.TransDate BETWEEN '1/1/2011' and '12/31/2011'

For SQL Server 2005+ you could also try: 对于SQL Server 2005+,您还可以尝试:

SELECT name, widgets, TransDate, Location
FROM (
       SELECT name, widgets, TransDate, Location, SUM(widgets) OVER(PARTITION BY Name) Quant
       FROM MyTable
       WHERE TransDate BETWEEN 1/1/2011 and 12/31/2011) A
WHERE Quant >= 16

This is assuming that the quota must be meeted on the same date frame. 这假设配额必须在同一日期框架内进行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM