读书人

SQL语句

发布时间: 2012-02-22 19:36:54 作者: rapoo

求一个SQL语句!

Delphi(Pascal) code
select code, sum(qty) as qty from                       (Select code,qty from indl                       union all                       select code,-qty from Tadd                       union all                       select code,-qty from outdl                       union all                       select code,sum(Inqty-Outqty) as qty from Inout group by code) aa                       where code='PPST0512457'                      group by Code';



我还想加一个条件,就是QTY 大于0,又不想重新来一次select 请问这个

where qty > 0 加在哪里?

[解决办法]
子查询加,或者后面加Having

SQL code
select code, sum(qty) as qty from                       (Select code,qty from indl where qty > 0                      union all                       select code,-qty from Tadd where qty > 0                      union all                       select code,-qty from outdl where qty > 0                      union all                       select code,sum(Inqty-Outqty) as qty from Inout where qty > 0 group by code) aa                       where code='PPST0512457' and where qty > 0                      group by Codeselect code, sum(qty) as qty from                       (Select code,qty from indl                       union all                       select code,-qty from Tadd                       union all                       select code,-qty from outdl                       union all                       select code,sum(Inqty-Outqty) as qty from Inout group by code) aa                       where code='PPST0512457'                      group by Code Having sum(qty)>0
[解决办法]
不要Having,就:

SQL code
select code, sum(qty) as qty from                       (Select code,qty from indl where qty > 0                      union all                       select code,-qty from Tadd where qty > 0                      union all                       select code,-qty from outdl where qty > 0                      union all                       select code,sum(Inqty-Outqty) as qty from Inout where qty > 0 group by code) aa                       where code='PPST0512457'                      group by Code
[解决办法]
应该是这样:
SQL code
select code, sum(case when qty>0 then qty else 0) as qty from                       (Select code,qty from indl                       union all                       select code,-qty from Tadd                       union all                       select code,-qty from outdl                       union all                       select code,sum(Inqty-Outqty) as qty from Inout group by code) aa                       where code='PPST0512457'                      group by Code'; 

读书人网 >.NET

热点推荐