SQL:尝试求和并加入2个表时获取重复数据

时间:2016-07-29 20:38:36

标签: sql

在本质上,我有两个表(购买和销售),我需要加入。两个表都有不同的主键,但它们共享相同的外键。每次购买时,都会创建一个新条目(使用它自己的主键)。每次进行销售时,都会创建一个新条目(使用自己的密钥)。

使用过的表的摘要:

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 Base中尝试脚本创建器时,它会给我产品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 Base称:

SQL状态:HY000 错误代码:1000

语法错误,意外的$ end,期待BETWEEN或IN或SQL_TOKEN_LIKE

2 个答案:

答案 0 :(得分:0)

感谢Jayvee,我得到了它的工作!

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"

答案 1 :(得分: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"