选择不带表SQL的值

时间:2014-01-08 21:31:28

标签: sql sql-server

我正在从此SQL Server表中获取项目[I1]并以- QTY- TOTAL返回此表..

http://i.stack.imgur.com/bdnPF.png

之后,我有另一行包含相同的项ID- QTY AND -Total

http://i.stack.imgur.com/4vUNP.png

我每次都需要过滤而不退回产品,

在这种情况下,当我要退回销售发票时,我已经退回了I1 ..我需要选择无退货产品,

    SELECT  
        DEL_PurchasesLines.ItemIdentityCode, 
        SUM(DEL_PurchasesLines.Qty) As Qty, 
        SUM(DEL_PurchasesLines.Total) As Total

    FROM DEL_PurchasesLines

    WHERE InvoiceNo = '1' AND DealerCode = 'S0002M'

    GROUP BY
        DEL_PurchasesLines.ItemIdentityCode

   HAVING SUM(DEL_PurchasesLines.Total) > 0 AND SUM(DEL_PurchasesLines.Qty) > 0

1 个答案:

答案 0 :(得分:1)

我总是喜欢在tempdb中创建一些测试数据。

--
-- Create sample data
--

use tempdb;
go

if object_id('items') > 0
drop table items
go

create table items
(
  id varchar(8),
  qty int,
  total int
);
go

insert into items values
('I1', 2, 4),
('I2', 3, 6),
('I3', 5, 10),
('I1', -2, -4);
go

select * from items;
go

解决此问题的一种方法是按ID分组,将qty和total列相加。仅显示具有>的行0

--
-- Show lines in which qty * total > 0
--

select id, sum(qty) as sum_qty, sum(total) as sum_total
from items
group by id
having sum(qty) > 0 and sum(total) > 0;

另一种想到这一点的方法是显示所有没有退货的订单。

--
-- Show rows that do not have any returns
--

select * 
from items i left join
(
    select id
    from items
    where qty < 0 or total < 0
) r on i.id = r.id
where r.id is null