获取日期值大于平均借贷利率的日期

时间:2018-09-12 17:23:22

标签: sql postgresql

我有一个名为BOOK的表(memberId,ISBN,dateBorrowed) 例如:

   isbn       |    memberId |   borrowed   
-------+---------------+-------------+----
9998-01-101-9 |             |           
9998-01-101-9 |             |            
9998-01-101-9 |             |            
9998-01-101-9 |        1000 | 2018-10-02
9998-01-101-9 |        1010 | 2018-09-04
9998-01-101-9 |        1021 | 2018-09-14
9998-01-101-9 |             |            
9998-01-101-9 |        1001 | 2018-10-02

我必须选择全部dates,其中每天借出的图书总数要比平均每天都要多。怎么做?

我选择了日期,并选择了几次:

SELECT borrowed, COUNT(*) AS dates 
  FROM BOOK
  WHERE borrowed IS NOT NULL
  GROUP BY borrowed;

我写的另一个查询是计算平均值:

SELECT SUM(dates)/COUNT(borrowed) AS average 
  FROM (
    SELECT borrowed, COUNT(*) AS dates 
      FROM BOOKS
      WHERE borrowed IS NOT NULL GROUP BY borrowed
  ) AS average;

现在,如何将这两个续集串联成一个清晰的续集?

1 个答案:

答案 0 :(得分:0)

这看起来有点像硬件,所以窗口函数可能超出范围。

SELECT * 
  FROM (
    SELECT BOOK.*,
           CAST(
           COUNT(1) OVER 
             ( PARTITION BY borrowed
             ) AS FLOAT) cntThatDay,
           CAST(
           SUM(1) OVER() AS FLOAT)/ CAST(
               (SELECT COUNT(DISTINCT borrowed)
                  FROM BOOKS 
               ) AS FLOAT) AS totalAverage
      FROM BOOK 
     WHERE borrowed IS NOT NULL
    ) TMP
WHERE cntThatDay >= totalAverage;