如何在特定的select语句中组合计数?

时间:2016-05-30 09:45:57

标签: sql postgresql

在我们的postgresql数据库中,我们目前有两个名为Users and Bookings的表。

我们目前正在尝试了解昨天预订了多少次预订的用户。

以下是我们目前的查询:

@Service
public class Test {

public Test(){
    ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
}

public static void main(String[] args) {
    Test test=new Test();
}
}

public class NoClassDefFoundErrorDemo {

public static void main(String[] args) {
    try {
        // The following line would throw ExceptionInInitializerError
        SimpleCalculator calculator1 = new SimpleCalculator();
    } catch (Throwable t) {
        t.printStackTrace();
    }
    // The following line would cause NoClassDefFoundError
    SimpleCalculator calculator2 = new SimpleCalculator();
}

}

class SimpleCalculator{
  static int undefined = 1 / 0;
}

如果我们在昨天使用过滤器创建了预订日期(字段“domain.bookings.created_at”),我们只会从昨天获取数据。

有没有办法看看谁昨天买了多少次超时预订?

谢谢! 卢卡

3 个答案:

答案 0 :(得分:0)

尝试这个

SELECT "domain".users.email, COUNT(CASE WHEN bookingdate = current_date - 1 THEN 1 END ) AS TOTAL_BOOKING
FROM "domain".bookings
INNER JOIN "domain".users ON "domain".users."id" = "domain".bookings.user_id
GROUP BY "domain".users.email

答案 1 :(得分:0)

感谢您的回答。我可能不够精确!

基本上,如果我使用以下查询:

SELECT
"domain".users.email,
COUNT( "domain".bookings."id") AS "Total Bookings"
FROM
"domain".bookings
INNER JOIN "domain".users ON "domain".users."id" = "domain".bookings.user_id    
GROUP BY
"domain".users.email

我得到了用户预订的数量。

但是

我想得到以下内容:昨天购买的用户一直在预订的数量。

我试过这个

SELECT
"domain".users.email,
COUNT( "domain".bookings."id") AS "Total Bookings"
FROM
"domain".bookings
INNER JOIN "domain".users ON "domain".users."id" = "domain".bookings.user_id    
WHERE
"domain".bookings.created_at = 'yesterday'
GROUP BY
"domain".users.email

但我没有得到回应......

谢谢你的帮助!

卢卡

答案 2 :(得分:0)

这就是你要找的东西:

SELECT u.id, u.email, count(b.id) AS "Total Bookings" 
FROM "domain".bookings as b
  JOIN "domain".users as U ON u.id = b.user_id
WHERE EXISTS (SELECT 1 
              FROM "domain".bookings b2
              WHERE b2.created_at = current_date - 1
                AND b2.user_id = b.user_id)
GROUP BY u.email;

对于昨天预订了某些内容的用户,exists条件只返回bookings表中的行。

不相关,但是:使用像domain这样需要双引号标识符的关键字并不是一个好主意。如果你找到一个不同的名字

,从长远来看会给你省点麻烦