2016-06-30 24 views
1

我需要将每个pvkey的金额相加,并且只有那些应该列出的total_amount >= 250的pvkeys应该列出,并且它们取决于某个年份/日期。如何根据日期计算每个pvkey,并且必须大于等于250

select finance.pvkey,sum(amount) from finance 
inner join contact 
on contact.pvkey = finance.pvkey 
where rectype='TOP_MAJDON'or rectype='MAJ_DON' or rectype='MEMBER'or rectype='MAJORDON' 
and transdate between '2015-01-01' and '2015-12-31' and amount >=250 
group by finance.pvkey 

我得到的结果,但他们中的一些是不正确的,有的则是小于250,他们不是内部某个日期之间(“2015年1月1日”和“2015年12月31日” )。

+0

Hi @ garincha03一件事:确保你的转换有以下'CONVERT(char(10),transdate,126)BETWEEN'2015-01-01'和'2015-12-31''使用sqlserver。您需要提及您使用的是什么类型的数据引擎 –

回答

1

当一起使用ORAND就必须有括号 像这样:

(rectype='TOP_MAJDON'or rectype='MAJ_DON' or rectype='MEMBER'or rectype='MAJORDON') 
and transdate between '2015-01-01' and '2015-12-31' and amount >=250 

otherwize,你不会得到你想要的东西具有聚合函数滤波器

1

使用

select finance.pvkey,sum(amount) from finance 
inner join contact 
on contact.pvkey = finance.pvkey 
where rectype='TOP_MAJDON'or rectype='MAJ_DON' or rectype='MEMBER'or rectype='MAJORDON' 
and transdate between '2015-01-01' and '2015-12-31' 
group by finance.pvkey 
having amount >=250 
+0

错误的订单... GROUP BY在HAVING之前。 – jarlh

+0

@jarlh谢谢回答更新 – scaisEdge

1

您需要修复您的where条款并添加having条款。我会建议使用inwhere

select f.pvkey, sum(amount) 
from finance f inner join 
    contact c 
    on c.pvkey = f.pvkey 
where rectype in ('TOP_MAJDON', 'MAJ_DON', 'MEMBER', 'MAJORDON') and 
     transdate between '2015-01-01' and '2015-12-31' 
group by f.pvkey 
having sum(amount) >= 250; 

注:我假设“TOTAL_AMOUNT”的问题是指sum(amount)。如果它实际上是指amount,则将比较保留在where子句中。

我应该补充一点:您在条件下似乎对andor感到困惑。在你对这样的逻辑感到满意之前,我建议你在你的条件表达式周围使用括号。

相关问题