如何在另一个表中按计数按组筛选一个表

时间:2016-02-19 18:08:31

标签: sql postgresql

我有一张coupons表和一张名为coupon_uses的第二张表。 coupons具有max_uses整数属性,用于限制优惠券的使用次数。每次使用优惠券时,都会创建coupon_uses条记录。

------------   ---------------
| coupons  |   | coupon_uses |
|----------|   |-------------|
| id       |   | coupon_id   |
| code     |   | ...         |
| max_uses |   ---------------
-----------

我如何构建一个查询,根据特定优惠券有多少相应的优惠券?我可以过滤优惠券表?例如,我希望使用的所有优惠券的次数少于其max_uses属性允许的次数。

3 个答案:

答案 0 :(得分:1)

这应该可以满足您的需求;

SELECT  c.max_uses ,
    c.id ,
    c.code ,
    COUNT(coupon_id) AS 'uses'
FROM    coupon_uses cu
    LEFT JOIN coupons c ON c.ID = cu.ID
GROUP BY c.max_uses ,
    c.id ,
    c.code    
  Having c.max_uses > count(coupon_id)

答案 1 :(得分:1)

---  The coupons which are already used to its max limit
SELECT  count(cu.*), cp.id, cp.max_uses 
FROM coupons cp
LEFT JOIN coupon_uses cu ON cp.id = cu.coupon_id
GROUP BY cp.id, cp.max_uses
HAVING  count(cu.*) =  cp.max_uses

--  The coupons which are remaining 
SELECT  count(cu.*), cp.id, cp.max_uses , cp.max_uses - count(cu.*) AS remaing_usage
FROM coupons cp
LEFT JOIN coupon_uses cu ON cp.id = cu.coupon_id
GROUP BY cp.id, cp.max_uses
HAVING  count(cu.*) <  cp.max_uses

答案 2 :(得分:0)

具有0次使用的优惠券在左连接中将获得1的计数。 因此,我使用UNION来计算使用过的优惠券,而不是单独使用。

- (void)extendBackgroundRunningTime {
    if (_backgroundTask != UIBackgroundTaskInvalid) {
        // if we are in here, that means the background task is already running.
        // don't restart it.
        return;
    }
    NSLog(@"Attempting to extend background running time");

    __block Boolean self_terminate = YES;

    _backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithName:@"DummyTask" expirationHandler:^{
        NSLog(@"Background task expired by iOS");
        if (self_terminate) {
            [[UIApplication sharedApplication] endBackgroundTask:_backgroundTask];
            _backgroundTask = UIBackgroundTaskInvalid;
        }
    }];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSLog(@"Background task started");

        while (true) {
            NSLog(@"background time remaining: %8.2f", [UIApplication sharedApplication].backgroundTimeRemaining);
            [NSThread sleepForTimeInterval:1];
        }

    });
}