2014-09-04 59 views
0

概括地說,就查詢結構而言,我完全在這裏做什麼。我試圖將兩個qry與一個聯盟結合在一起,輸出不是我想要的。計數記錄<1500 and > = 1500

下面是兩個表,我需要列

帳戶表: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) 
) 

這是最好的方式來做到這一點?我得到一個數據集,但基本上堆疊在一起。我希望數據合併本質上....

更新:「案件時」再次罷工。這就是爲什麼我喜歡這個網站,人們在那裏拉你走出雜草!

回答

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) 
+2

你不需要WHERE子句 – InitK 2014-09-04 18:37:10

+1

夠正確。我只是把它包括在內,因爲它是在原來的。我沒有看那麼近,但仔細看時確實很傻。 :) – 2014-09-04 18:41:54

+0

去圖,一個案例聲明。非常感謝。這完全有效,在where子句中,我得到的記錄少一個。我認爲沒有條款是我們需要的。太感謝了。 – donviti 2014-09-04 18:46:58

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展示概念(在低得多的比例)

+0

好的,這給了我一個結果,但我正在尋找兩個單獨的結果<1500 and > = 1500。肖恩的答案有效。謝謝您的幫助。 – donviti 2014-09-04 18:51:08