我的查询
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
错误。
如何在子查询中使用sum。
我正在使用postgresql 9.1
编辑:
我想得到acduebills
表中的行数,即(acb.opening + acb.debit-acb.credit)&gt; 0和acb.unitname ='销售'。在那之后我想得到相同条件下最小日期的一天的差异。在那之后,我想要开放,它来自两个表:acledgerbal
和acvoucher2
。 acvoucher
条件检查txdate
表格。
如何在单个查询中获取这些细节?如何在多个模式中获取相同的详细信息?
答案 0 :(得分: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')
答案 1 :(得分: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
类型,所以我投了总和。