mysql - SQL 查询连接 4 个表并从 2 个不同的表中获取 2 列的总和

标签 mysql sql join casting

表 1:采购报告

|id| VoucherNO| VoucherDate|
+--+----------+------------+
|1 |  0001    |  28/9/2017 |
|2 |  0010    |  27/9/2017 |

Table 2: Detail Purchase Report

|id | ITEMID | QTYpurchased | voucher
+---+--------+--------------+--------
|1  |   101  | 12           |   0001
|2  |   120  | 25           |   0001
|3  |   121  | 21           |   0014

Table 3: Sale Report

|id| VoucherNO| VoucherDate|
+--+----------+------------+
|1 |  0025    |  25/9/2017 |
|2 |  0058    |  23/9/2017 |

Table 4: Detail Sale

|id | ITEMID | QTYpurchased | voucher
+---+--------+--------------+--------
|1  |  101   |  8           |   0025
|2  |  120   |  5           |   0025
|3  |  121   | 10           |   0058

Objective of the query is to join all 4 Tables to return 2 Columns ie.,

  • Column 1 : Item Name
  • 2 : Difference Purchased qty and sold qty having same item id in between given dates gives the qty of a item at that particular date.

Query I tried is as follows

SELECT
  A.ITEMN, 
  A.ITEMNAME,
  SUM(CAST(C.QUANTITY AS numeric(18,2))) - SUM(CAST(A.QTY AS numeric(18,2))) as QTY 
FROM DETAILSALE A, SALESREPORT B, DETAILPURCHASES C, PURCHASEREPORT D 
WHERE A.BARCODE = B.VOUCHERNO 
  AND  C.BARCODE = D.VOUCHERNO 
  AND D.VOUCHERDATE=B.VOUCHERDATE
  AND D.VOUCHERDATE BETWEEN '" & DATE1.Text & "' AND '" & DATE2.Text & "'   
GROUP BY A.ITEMN,A.ITEMNAME 
ORDER BY A.ITEMN ASC

要求的输出:

| ITEMID | QTY |
+--------+-----+
|  101   | 2   |
|  120   | 10  |
|  121   | 10  |

最佳答案

先聚合,然后才加入。我从您的描述中遗漏了一个产品表,并且您的表描述和查询中的名称不匹配,因此您可能需要调整我的查询中的名称:

select
  product.id,
  product.name,
  purchases.total,
  sales.total
from product
left join
(
  select itemid, sum(quantity) as total
  from detail_purchase
  where voucher in (select voucher from purchase where date between date '2017-09-01' 
                                                                and date '2017-09-05')
  group by itemid
) purchases on purchases.itemid = product.itemid
left join
(
  select itemid, sum(quantity) as total
  from detail_sale
  where voucher in (select voucher from sale where date between date '2017-09-01'
                                                            and date '2017-09-05')
  group by itemid
) sales on sales.itemid = product.itemid;

如果您只想要购买和/或销售的产品,请将外部连接更改为内部连接。

关于mysql - SQL 查询连接 4 个表并从 2 个不同的表中获取 2 列的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46501034/

相关文章:

mysql - 获取两个用户之间的相互订阅

mysql - 将连接表从一行更新到另一行

sql - 如何从 Sql Server 中的 TimeZoneOffset 获知 TimeZone StandardName 或 DayLightName

SQL 比较具有共同 id 的两个表,但表 2 中的 id 可能位于两个不同的列中

mysql - 使用 Group_Concat 进行内连接

php - MySQL Join 将不匹配的记录包含在 WHERE 语句中

mysql - 从主机连接到 docker mysql

php - 使用相同的 php 表单添加/查看/编辑 mysql 条目

c# - 检查表在 SQL Azure 中是否存在

mysql - SQL 按日期降序排序表达式