簡體   English   中英

MySql:來自兩個不同表的兩個列的總和

[英]MySql: Sum of two columns from two different tables

這可能是重復問題 ,但是我的問題沒有解決。

我正在嘗試使用日期確定物品的內向和外向
表。

  • 在表1中,我們簡稱為A 我將擁有三列,即A_DtA_NaA_Qty
  • 在表2中,我們簡稱為“ B”。 我將擁有三列,即B_DtB_N a, B_Qty
  • 在表3中,我們將其簡稱為“ C”。 我將擁有三列,即C_DtC_N a, C_Qty

  • 表A和B向內,C向外。
    我使用了修改后的查詢,但添加了第三列。

    表示例:

    C_Dt       C_Na  C_Qty
    2016-08-01  XY  150
    2016-08-03  XY  100
    2016-08-04  XY  200
    

    表B:

    Date           Inward   Outward
    2016-08-01      200      150
    2016-08-02      100      0
    2016-08-03      100      100
    2016-08-04      200      200
    2016-08-05      150      0
    

    表C:

     C_Dt C_Na C_Qty 2016-08-01 XY 150 2016-08-03 XY 100 2016-08-04 XY 200 

    預期產量

     Date Inward Outward 2016-08-01 200 150 2016-08-02 100 0 2016-08-03 100 100 2016-08-04 200 200 2016-08-05 150 0 

    好吧,在這種情況下,我應該使用左連接,否則必須執行以下查詢。

    查詢:

     select t.Dt as Date, sum(t.Qty) as Inward,sum(t.outward) as outward1 from( select A_Dt as Dt, A_Na as Na, A_Qty as Qty from a union all select B_Dt as Dt, B_Na as Na, B_Qty as Qty from b union all select C_Dt as Dt, C_Na as Na, C_Qty as outward from c )t group by t.Dt, t.Na order by t.Dt; 

    跟隨錯誤:

     #1054 - Unknown column 't.outward' in 'field list' 

    任何想法都會很棒。

    首先使用union all將兩個表數據合並為一個,然后找到按日期和Na列分組的數量總和。

    詢問

    select t.Dt, t.Na as Inward, sum(t.Qty) as Outward from(
        select A_Dt as Dt, A_Na as Na, A_Qty as Qty from Table_A
        union all
        select B_Dt as Dt, B_Na as Na, B_Qty as Qty from Table_B
    )t
    group by t.Dt, t.Na
    order by t.Dt;
    

    編輯

    實際上,實際上現在不需要合並TableC的數據,但是您必須使用聯接。

    詢問

    select t1.Dt, t1.Qty as Inward, coalesce(t2.C_Qty, 0) as Outward from(
        select t.Dt, t.Na, sum(t.Qty) as Qty from(
            select A_Dt as Dt, A_Na as Na, A_Qty as Qty from Table_A
            union all
            select B_Dt as Dt, B_Na as Na, B_Qty as Qty from Table_B
        )t
        group by t.Dt, t.Na
    )t1
    left join Table_C t2
    on t1.Dt = t2.C_Dt
    order by 1;
    

    結果

    +============+========+=========+
    | Dt         | Inward | Outward |
    +------------+--------+---------+
    | 2016-08-01 | 200    | 150     |
    | 2016-08-02 | 100    | 0       |
    | 2016-08-03 | 100    | 100     |
    | 2016-08-04 | 200    | 200     |
    | 2016-08-05 | 150    | 0       |
    +============+========+=========+
    

    您的查詢只需要稍作更正

    select t.Dt as Date, sum(t.Qty) as Inward, sum(t.outward) as outward1 from(
       select A_Dt as Dt, A_Na as Na, A_Qty as Qty, 0 as outward from a
       union all
       select B_Dt as Dt, B_Na as Na, B_Qty as Qty, 0 as outward from b
       union all
       select C_Dt as Dt, C_Na as Na, 0 as Qty, C_Qty as outward from c
    )t
    -- where Na = 'XY'
    group by t.Dt, t.Na
    order by t.Dt;
    

    暫無
    暫無

    聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

     
    粵ICP備18138465號  © 2020-2024 STACKOOM.COM