简体   繁体   中英

Scalar subqueries produced more than one element

I know this error has been produced many time and a lot of answers came by but I believe every situation might be unique.

So i am trying to get a deficit value(imports - exports) from a table. Both values are on one column

value account
100  export
200  import

SO now i need to calculate the deficit or surplus, which is either import-export or export-import. I tried scalar subqueries but i am always getting this error.

SELECT label, product_type,status,((select value from Task2.quarterly_report where account="Imports") - (select value from Task2.quarterly_report where account="Exports")) As trade_deficit

so basically i am trying to get a table with:-

label  product_type status trade_deficit

Can anyone explain to me the issue and why is it happening and how to solve it. Thanks in advance

You can use the conditional aggregation:

select sum(case when account = 'import' then value
                when account = 'export' then - value
           end)
from t;

This is based on the question and sample data. I don't see what your query has to do with the rest of the question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM