2016-07-29 47 views
1

在Essence中,我需要將兩個表(購買和銷售)結合在一起。兩個表具有不同的主鍵,但它們共享相同的外鍵。每次進行購買時,都會創建一個新條目(使用它自己的主鍵)。每次進行銷售時,都會創建一個新條目(使用自己的密鑰)。SQL:嘗試彙總並加入2個表時獲取重複數據

彙總使用的表:

Purchase Data 
    Individual Product Cost (AS IPC) 
    Sales Tax (AS ST) 
    Quantity (AS Q) 
    SKU (Foreign Key) 
    Primary Key (AS PK) 

Sales 
    Amount Sold (AS AS) 
    Total (AS T) 
    SSKU(Foreign Key) 
    Primary Key (AS PK) 

當我試圖總結和加入基於產品我會有奇怪的結果數據。

採購表的數據:

SKU | IPC | ST | Q | PK 
    1 2.40 .02 5 1 
    2 5.00 .05 20 2 
    3 4.00 .04 5 3 
    1 5.00 .04 20 4 

銷售表:

SSKU | T | AS | PK 
    1  10  2 1 
    2  9  1 2 
    3  9  4 3 
    1  9  1 4 
    2  9  2 5 
    1  9  2 6 
    1  9  4 7 

預期結果

SKU | (IPC + ST)Q | Q | SUM AS | SUM T 
    1   354.9  25  9  37 
    2   101   20  3  9 
    3   80.8   5  4  18 

當試圖在OpenOffice的基礎劇本創作者,它會給我預期的結果對於產品3,但對於產品1和產品2是錯誤的。

我閱讀了SQL編程,並嘗試了一下。我認爲這可以通過在合併之前分開總結兩個表來解決問題。相反,我現在一直收到一個錯誤,我找不到錯誤。

目前代碼:

SELECT 

"A"."SKU" 
,SUM(("A"."Individual Product Cost" + "A"."Sales Tax") * "A"."Quantity") 
,"A"."Quantity" 
,"D"."Sales" 
,"D"."Sold" 

FROM "PurchaseData" AS "A" 

Inner Join 

(

Select 
"ACT"."SSKU" 
,SUM("ACT"."Amount Sold") AS Sold 
,SUM("ACT"."Total") AS Sales 

From 
"Sales" AS ACT 

GROUP BY 
"ACT"."SSKU" 
) 

AS D  

on "A"."SKU" = "D"."SSKU" 


Group By 
"A"."SKU" 

編輯: 根據隨機在線語法檢查器,它的3線(我看不出來)。 根據OpenOffice的基礎:

SQL狀態:HY000 錯誤代碼:1000

語法錯誤,意想不到的$結束,預計間或或SQL_TOKEN_LIKE

+0

什麼錯誤? –

+0

根據一個隨機語法檢查器,其在第3行根據OpenOffice的底座: 語法錯誤在SQL表達式 SQL狀態:HY000 錯誤代碼:1000 在SQL表達式 SQL狀態語法錯誤:HY000 錯誤代碼:1000 語法錯誤,意外的$ end,期望BETWEEN或IN或SQL_TOKEN_LIKE – midir

+1

您可以在子查詢中對購買數據進行求和,就像您對銷售進行求和一樣,然後將兩個子查詢合併在一起,而無需彙總 – Jayvee

回答

0

多虧了二隊,我得到它的工作!

Select 
"A"."SKU" 
,"B"."Sold" 
,"B"."Sales" 
,"A"."Total Cost" 
,"A"."Total Purchased" 

From 

-- First Sub Query -- 
(
Select 

"PD"."SKU" As SKU 
,SUM(("PD"."Individual Product Cost" + "PD"."Sales Tax") *"PD"."Quantity") AS "Total Cost" 
,SUM ("PD"."Quantity") AS "Total Purchased" 

From 
"PurchaseData" AS PD 

GROUP BY 
"PD"."SKU" 
) 
As A 

--End First-- 

Join 
--Start 2nd-- 
(
Select 

"ACT"."SSKU" AS ASKU 
,SUM("ACT"."Amount Sold") AS Sold 
,SUM("ACT"."Total") AS Sales 

From 
"Sales" As ACT 

GROUP BY 
"ACT"."SSKU" 
) 
As B 
--End 2nd-- 

On 
"B"."ASKU" = "A"."SKU" 
0

,你可以在一個子查詢總結購買數據,同樣爲您提供銷售做了,然後再加入兩個子查詢中而不凝集:

Select 
"A"."SKU" 
,"B"."Sold" 
,"B"."Sales" 
,"A"."Total Cost" 
,"A"."Total Purchased" 

From 

-- First Sub Query -- 
(
Select 

"PD"."SKU" As SKU 
,SUM(("PD"."Individual Product Cost" + "PD"."Sales Tax") *"PD"."Quantity") AS "Total Cost" 
,SUM ("PD"."Quantity") AS "Total Purchased" 

From 
"PurchaseData" AS PD 

GROUP BY 
"PD"."SKU" 
) 
As A 

--End First-- 

Join 
--Start 2nd-- 
(
Select 

"ACT"."SSKU" AS ASKU 
,SUM("ACT"."Amount Sold") AS Sold 
,SUM("ACT"."Total") AS Sales 

From 
"Sales" As ACT 

GROUP BY 
"ACT"."SSKU" 
) 
As B 
--End 2nd-- 

On 
"B"."ASKU" = "A"."SKU"