Home > Database > Mysql Tutorial > How Can I Display Unique Dates When Merging Inbound and Outbound Product Movement Data in SQL?

How Can I Display Unique Dates When Merging Inbound and Outbound Product Movement Data in SQL?

DDD
Release: 2024-12-25 22:42:10
Original
293 people have browsed it

How Can I Display Unique Dates When Merging Inbound and Outbound Product Movement Data in SQL?

Merging Tables and Unifying Dates

In SQL, combining data from multiple tables is essential for comprehensive analysis. This problem requires merging two tables, Inbound and Outbound, which track product movements. The initial query effectively merges these tables, but there is an additional requirement to display the dates uniquely.

Unique Date Display Using UNION ALL and GROUP BY

To achieve unique date display, the original query can be modified to use UNION ALL in conjunction with GROUP BY:

SELECT Date, Product, SUM(Inbound) as Inbound, SUM(Outbound) as Outbound
FROM ((SELECT Inbound_Date As Date, Product, SUM(Quantity) as Inbound, 0 as Outbound
      FROM Inbound
      GROUP BY 1,2
     ) UNION ALL
     (SELECT Outbound_Date, Product, 0 as Inbound, COUNT(*)  as Outbound 
      FROM Outbound
      GROUP BY 1,2
     )
    ) io
GROUP BY Date, Product;
Copy after login

Breakdown of the Changes:

  • The UNION ALL combines the results of two subqueries, each representing one of the original tables.
  • The subqueries group the data by Inbound_Date (aliased as Date) and Product for Inbound and by Outbound_Date and Product for Outbound.
  • By nesting these subqueries, Inbound and Outbound quantities are separated into columns.
  • The outer GROUP BY clause further aggregates the data by Date and Product, ensuring that duplicate dates are removed.

Output Interpretation:

The modified query produces the desired output:

Date Product Inbound Outbound
2017-05-23 Product A 400 1
2017-09-04 Product C 380 0
2017-10-18 Product C 0 1
... ... ... ...
2018-09-10 Product B 200 1
... ... ... ...

The above is the detailed content of How Can I Display Unique Dates When Merging Inbound and Outbound Product Movement Data in SQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template