SQL Server查询问题

时间:2015-01-25 18:58:53

标签: sql-server

在下面的查询中,我从otherexpensecost表中选择loadingcost和unloadingcost以及运费。但是我想检查一下,如果GoodsReceivedNoteDetails表中的goodsreceivednoteid计数超过1,它应该从GoodsReceivedNoteDetailtable获得,否则应该从otherexpensecost表获得装载和卸载费用和运费。但是在下面的查询中,我从otherexpense成本表中获得了装载成本,卸载和运费,而没有检查GoodsReceivedNoteDetail中的GoodsReceivedNoteID的数量。

表1其他费用成本:

GoodsReceivedNoteID
LoadingCost
UnloadingCost
FreightCharges

表2 GoodsReceivedNoteDetail

GoodsReceivedNoteID
GoodsreceivedNoteDetailID
ProductID
LoadingCost
UnloadingCost
FreightCharges  

查询:

SELECT      
    GRN.GoodsReceivedNoteNo,
    GRN.LocationID,
    GRN.CreatedOn,
    PO.PurchaseOrderNo,
    V.VendorName,
    GRN.SupplierInvoiceNo,
    GRN.SupplierInvoiceDate,
    SR.LRNO,
    T.TransporterName,
    ISNULL((OEC.FreightCharges), 0.00) FreightCharge,
    ISNULL((OEC.LoadingCost+OEC.UnloadingCost), 0.00) LoadingandUnloadingcharges,
    P.ProductCode,
    P.ProductName,
    GRND.ReceivedQuantity,
    GRND.RejectedQuantity,
    GRND.AcceptedQuantity,
    GRND.UnitPrice AS BasicRate,
    ISNULL((GRND.UnitPrice * GRND.ReceivedQuantity), 0.00) BasicValue,
    GRND.VAT,
    ISNULL((OEC.FreightCharges), 0.00) AS FreightApporitioned,
    ISNULL((OEC.LoadingCost + OEC.UnloadingCost), 0.00) AS LoadingandUnloadingApportioned,
    ISNULL((GRND.UnitPrice + OEC.FreightCharges + OEC.LoadingCost + OEC.UnloadingCost), 0.00) AS TotalCost
FROM 
    GoodsReceivedNoteDetail GRND
LEFT OUTER JOIN 
    GoodsReceivedNote GRN ON GRN.GoodsReceivedNoteID = GRND.GoodsReceivedNoteID 
LEFT OUTER JOIN 
    PurchaseOrder PO ON PO.PurchaseOrderID = GRN.PurchaseOrderID
LEFT OUTER JOIN 
    Vendor V ON V.VendorID = PO.VendorID
LEFT OUTER JOIN 
    SecurityRegister SR ON SR.SecurityRegisterID = GRN.SecurityRegisterID
LEFT OUTER JOIN 
    Transporter T ON T.TransporterID = SR.TransporterID
LEFT OUTER JOIN 
    OtherExpenseCost OEC ON OEC.GoodsReceivedNoteID = GRN.GoodsReceivedNoteID 
LEFT OUTER JOIN 
    Product P ON P.ProductID = GRND.ProductID
WHERE 
   GRND.CreatedOn >= @d_StartDate 
   AND  GRN.LocationID = @i_LocationID 
   AND GRND.CreatedOn <= @d_EndDate 
END

1 个答案:

答案 0 :(得分:0)

使用window function查找每个count的{​​{1}}。尝试这样的事情。

GoodsReceivedNoteID