2014-03-07 56 views
1

我的查詢是琛子查詢

select count(*) as cnt, 
     EXTRACT(day FROM current_date - min(txdate))::int as days, 

     sum (Select opening from acledgerbal l 
       where acname='Arv' 
       union all 
       Select sum(v2.debit-v2.credit) as opening from acvoucher2 v2 where 
       txdate<='05/03/2014') as opening 

from acduebills acb,acledger l 

where (acb.opening+acb.debit-acb.credit) > 0 
    and acb.unitname='Sales' 
    and l.acname='Arv' 
    and l.acno=acb.acno 

這表明more than one row returned by a subquery used as an expression錯誤。 如何使用子查詢的總和。

我使用PostgreSQL 9.1

編輯:

我想要得到的行數在acduebills表是(acb.opening + acb.debit-acb.credit)> 0, acb.unitname = '銷售'。之後,想在同一條件下得到最小日期的差異。之後,我想要開放,它來自兩個表格:acledgerbalacvoucher2acvouchertxdate條件檢查。

如何在單個查詢中獲取這些詳細信息?如何在多個模式中獲取相同的細節?

+0

這裏有一個語法錯誤:''從acvoucher2 v2,txdate <='05/03/2014'',可能缺少where子句,請檢查查詢。 – krokodilko

+1

這是在多個地方打破。而且你沒有提供足夠的信息來修復它 –

+0

現在好多了。 'txdate'的類型是'date'?並從哪個表? 「acduebills」和「acledger」如何連接? –

回答

1

像這樣的東西:

SELECT count(*) AS cnt 
    , current_date - min(txdate)::date AS days -- subtract dates directly 

    , (SELECT round(sum(opening)::numeric, 2) 
     FROM (
      SELECT opening 
      FROM acledgerbal 
      WHERE acname = 'Arv' 

      UNION ALL 
      SELECT debit - credit 
      FROM acvoucher2 
      WHERE txdate <= '2014-05-03' 
      ) sub 
     ) AS opening 
FROM acduebills b 
JOIN acledger l USING (acno) 
WHERE ((b.opening + b.debit) - b.credit) > 0 
AND b.unitname ='Sales' 
AND l.acname = 'Arv'; 

round()到小數位只適用於numeric類型,所以我投的總和。

+0

謝謝先生的工作 – Sathish

+0

先生我編輯我的問題。你能得到任何信息嗎?對不起,我的英語 – Sathish

+0

@SATSON:增加了一點。 –

1

在這裏發表聲明如下問題:

sum ( Select opening from acledgerbal l 
      where acname='Arv' 
      union all 
      Select sum(v2.debit-v2.credit) as opening from acvoucher2 v2, 
      txdate<='05/03/2014') 

您使用UNION所以這個子查詢返回至少2行。所以,你會得到一個錯誤,子查詢不能返回多個行:

嘗試將其更改爲「被用作表達式的子查詢返回多行」:

(Select SUM(opening) from acledgerbal l WHERE acname='Arv') 
    + 
    (Select SUM(v2.debit-v2.credit) as opening from acvoucher2 v2 
              WHERE txdate<='05/03/2014')