SQL有三行输出,需要一行

时间:2017-02-13 17:40:28

标签: sql-server case

我有一个项目,我需要总结发票,大部分都很简单,因为我只是从Invoice_master表中读取。我还需要根据位置总结两个字段。我能够获得数据,但每张发票都有三行输出。我怎么把它归结为一个?

select INVCE_31 as "Invoice Number",
    CAST(INVDTE_31 as date) as "Invoice Date",
    CUSTID_31 as "Customer ID",
    ORDNUM_31 as "Sales Order",
    LNETOT_31 - ORDDSC_31 as "Net Amount",
    FRTAMT_31 as "Freight Amount",
    TAXTOT_31 as "Tax Total",
    TAX1_31 as "Invoice Tax",
    LNETOT_31 as "Inovice Total",
    sum(case 
            when ID.STK_32 = 'SAMPLE'
                then PRICE_32
            else 0
            end) as LOCSAMPLE,
    sum(case 
            when ID.STK_32 = 'LITERTRE'
                then PRICE_32
            else 0
            end) as LOCLITERTRE
from Invoice_Master im
left join Invoice_Detail id on im.INVCE_31 = id.INVCE_32
where INVCE_31 = '00084048'
group by ID.STK_32,
    IM.INVCE_31,
    IM.INVDTE_31,
    IM.CUSTID_31,
    IM.ORDNUM_31,
    IM.LNETOT_31,
    IM.TAX1_31,
    IM.ORDDSC_31,
    IM.FRTAMT_31,
    IM.TAXTOT_31

输出:

 Invoice Number Invoice Date    Customer ID Sales Order Net Amount  Freight Amount  Tax Total   Invoice Tax Inovice Total   LOCSAMPLE   LOCLITERTRE
 00084048       2016-06-30       BAYKIT      20088547   4549.61             20       4569.61    319.87      12708.4          0           793.72
 00084048       2016-06-30       BAYKIT      20088547   4549.61             20       4569.61    319.87      12708.4          0           0
 00084048       2016-06-30       BAYKIT      20088547   4549.61             20       4569.61    319.87      12708.4          213         0

2 个答案:

答案 0 :(得分:0)

您可能希望在GROUP BY而不是CAST(INVDTE_31 as date)上使用INVDTE_31,如果在同一日期但时间不同的情况下有多条记录,则会产生重复:

select invce_31 as "invoice number",
    cast(invdte_31 as date) as "invoice date",
    custid_31 as "customer id",
    ordnum_31 as "sales order",
    lnetot_31 - orddsc_31 as "net amount",
    frtamt_31 as "freight amount",
    taxtot_31 as "tax total",
    tax1_31 as "invoice tax",
    lnetot_31 as "inovice total",
    sum(case 
            when id.stk_32 = 'sample'
                then price_32
            else 0
            end) as locsample,
    sum(case 
            when id.stk_32 = 'litertre'
                then price_32
            else 0
            end) as loclitertre
from invoice_master im
left join invoice_detail id on im.invce_31 = id.invce_32
where invce_31 = '00084048'
group by im.invce_31,
    cast(invdte_31 as date),
    im.custid_31,
    im.ordnum_31,
    im.lnetot_31,
    im.tax1_31,
    lnetot_31 - orddsc_31,
    im.frtamt_31,
    im.taxtot_31

答案 1 :(得分:0)

您正在使用分组子句中的Invoice_Detail表中的ID.STK_32。 如果ID.STK_32值' LITERTRE',' SAMPLE'和其他可以出现在一张发票上会导致重复。