2013-11-27 62 views
1

我有這個MySQL語句,它返回我們所有經銷商的列表以及他們擁有的商店總數。我試圖做到這一點,以便我可以添加額外的列,根據商店joineddate列返回。子查詢中的MySQL COUNT行

這是返回經銷商列表(帳戶組)和分配給帳戶組的商店總數/ COUNT的基本聲明。

SELECT accountgroup, COUNT(storename) AS TotalAmountOfStores 
FROM accounts 
WHERE accountgroup <>'' 
AND othercode ='Site' 
GROUP BY accountgroup 

我以爲在SELECT子查詢中使用下面的語句會讓我有這些額外的列,我想要的。這個聲明是獨立的,但是我沒能成功地將它作爲子查詢合併到上述聲明中。

SELECT COUNT(storename) AS '2months' 
FROM `accounts` 
WHERE joineddate > date_sub(now(), interval 2 month) 
AND accountgroup <> '' 
AND othercode = 'Site' 
GROUP BY accountgroup 

這是我想會的工作的說法,但我得到的錯誤「#1242 - 子查詢返回多個1行,這讓我困惑,因爲它應該返回多行」:

SELECT accountgroup, COUNT(storename) AS TotalAmountOfStores, 
(SELECT COUNT(storename) 
FROM `accounts` 
WHERE joineddate > date_sub(now(), interval 2 month) AND accountgroup <>'' AND othercode='Site' 
GROUP BY accountgroup) AS '2months' 
FROM accounts 
WHERE accountgroup <>'' 
AND othercode ='Site' 
GROUP BY accountgroup 

我開始覺得子查詢不是正確的方法,並且正在閱讀JOIN的。任何人都可以證實這一點,並可能指向正確的方向嗎?

任何幫助,非常感謝。提前致謝。

+0

您的預期輸出是什麼? –

+1

是的,我可以確認你應該閱讀連接 – Strawberry

回答

3

您可以使用if來合計這個條件爲真的時間。示例:

SELECT 
accountgroup, 
COUNT(storename) AS TotalAmountOfStores, 
SUM(
    IF(joineddate > date_sub(now(), interval 2 month), 1, 0) 
) AS '2months' 
FROM accounts 
WHERE accountgroup <>'' 
AND othercode ='Site' 
GROUP BY accountgroup