2014-01-08 32 views
0

我正在從這個SQL Server表項[I1],並返回到該表作爲- QTY- TOTAL值..沒有選擇 - 從表SQL

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 
+0

我需要過濾像 像 http://i.stack.imgur.com/e1rTj.png – Erric

+2

真煩人切換幻燈片... – Mihai

+1

一些'T-SQL'和一些樣品' Data'是大有幫助,然後口頭描述:) –

回答

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進行分組,總計列數和總數。僅顯示具有> 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 
+0

謝謝CRAFTY ,,,我明白了......謝謝...... :) – Erric

+0

我的榮幸。有很多方法可以考慮業務邏輯。獲得要求是困難的部分。保重 ... –