计数记录< 1500和> = 1500

时间:2014-09-04 18:22:32

标签: sql sql-server sql-server-2008 tsql

从概念上讲,就查询结构而言,我完全不知道该做什么。我试图将两个qry与一个联合组合在一起,输出不是我想要的。

以下是我需要的两个表格和列

帐户表:acct_no

金额表: acct_no, amount_id, AMT, 日期

我想要做的是计算< 1500以及文件数> = 1500

的记录数

它很简单我确定,我让它变得复杂

(
SELECT 
COUNT(acct_no) as GT1500,
Null as LT1500,
DATEPART(Year, amount.Date) Deposit_Year, 
DATEPART(QUARTER, amount.Date) Deposit_Qtr, 

 From account full outer JOIN amount ON account.AcctNo = amount.AcctNo
where amount < 1500 

group by
COUNT(amount.Date)as LT1500,
DATEPART(Year, amount.Date) Deposit_Year, 
DATEPART(QUARTER, amount.Date)
)

union all

(
SELECT 
Null as GT1500,
COUNT(acct_no)as LT1500,
DATEPART(Year, amount.Date) Deposit_Year, 
DATEPART(QUARTER, amount.Date) Deposit_Qtr, 

 From account full outer JOIN amount ON account.AcctNo = amount.AcctNo
where amount >= 1500 

group by
COUNT(amount.Date)as LT1500,
DATEPART(Year, amount.Date) Deposit_Year, 
DATEPART(QUARTER, amount.Date)
)

这是最好的方法吗?我获得了一个数据集,但基本上堆叠在一起。我希望数据基本合并......

更新:&#34;案例何时&#34;再次罢工。这就是为什么我喜欢这个网站,人们会把你赶出杂草!!!

2 个答案:

答案 0 :(得分:3)

这样的事情有点简单吗?

SELECT sum(case when amount > 1500 then 1 else 0 end) as GT1500
    , sum(case when amount < 1500 then 1 else 0 end) as LT1500
    , DATEPART(Year, amount.Date) Deposit_Year
    , DATEPART(QUARTER, amount.Date) Deposit_Qtr 
From account 
full outer JOIN amount ON account.AcctNo = amount.AcctNo
group by DATEPART(Year, amount.Date)
    , DATEPART(QUARTER, amount.Date)

答案 1 :(得分:1)

我相信这应该做你正在寻找的事情:

SELECT amount.acct_no, count(amount.acct_no)
FROM amount
join account on amount.acct_no = account.acct_no
WHERE amount.amt >= 1500
GROUP BY amount.acct_no
HAVING COUNT(amount.acct_no) < 1500

这是一个简单的sqlFiddle,展示了这个概念(规模要小得多)