相关子查询;任何月份和年份的付款都是该月份和年份的平均值的两倍多

时间:2016-12-01 21:47:51

标签: sql sql-server

完整问题:任何月份和年份的付款都是该月份和年度平均值的两倍以上

(即将2004年10月的所有付款与2004年10月的平均付款进行比较?按付款日期订购结果。您需要使用日期功能。)

我对sql的尝试

DECLARE @StartDate DATETIME, @EndDate DATETIME
SET @StartDate = DATEADD(mm, DATEDIFF(mm,0,getdate())-1, 0)
SET @EndDate = DATEADD(mm, 1, @StartDate)

SELECT checkNumber, amount AS avg_payment, paymentDate
FROM Payments 
WHERE paymentDate BETWEEN '2004-10-01' AND '2004-10-31'
AND amount > 2 * (SELECT AVG(amount)
                    FROM Payments 
GROUP BY paymentDate, checkNumber, amount)

数据库:http://richardtwatson.com/dm6e/images/general/ClassicModels.png

我做错了什么?

2 个答案:

答案 0 :(得分:2)

使用窗口函数可以轻松处理这类问题:

SELECT p.checkNumber, p.amount, p.paymentDate
FROM (SELECT p.*,
             AVG(p.amount) OVER (PARTITION BY YEAR(p.paymentDate), MONTH(p.PaymentDate)) as avg_ym
      FROM Payments p
     ) p
WHERE p.paymentDate BETWEEN '2004-10-01' AND '2004-10-31' AND
      p.amount > 2 * avg_ym;

正如评论中所提到的,您的查询首先没有工作,因为没有相关子句,第二,因为它会返回错误,因为返回的行太多。

答案 1 :(得分:0)

您应按年份(paymentDate),月份(paymentDate)分组,而不是payDate

  SELECT checkNumber, amount AS avg_payment, year(paymentDate), month(paymentDate)
  FROM Payments  
  WHERE paymentDate BETWEEN '2004-10-01' AND '2004-10-31'
  AND amount > 2 * (  SELECT AVG(amount)
                      FROM Payments 
                      WHERE paymentDate BETWEEN '2004-10-01' AND '2004-10-31'
                      GROUP BY  year(paymentDate), month(paymentDate),  checkNumber, amount)