Home > Database > Mysql Tutorial > How to Merge & Aggregate Inbound/Outbound Data with Unique Dates in SQL?

How to Merge & Aggregate Inbound/Outbound Data with Unique Dates in SQL?

Patricia Arquette
Release: 2024-12-27 00:06:10
Original
336 people have browsed it

How to Merge & Aggregate Inbound/Outbound Data with Unique Dates in SQL?

Merge Tables and Unique Date Values in SQL

The challenge involves merging two tables, Inbound and Outbound, while ensuring that the resulting table displays unique dates.

The provided VBA code successfully merges the tables using UNION ALL. However, to make the dates unique, a modification is needed.

The revised query employs both UNION ALL and GROUP BY. Specifically, it combines data from both tables into a single dataset using UNION ALL, then groups the results by Date and Product. This ensures that each combination of Date and Product appears only once in the merged table.

The final query is as follows:

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
     )
    ) AS io
GROUP BY Date, Product;
Copy after login

With this modification, the merged table will display unique dates while maintaining the desired data aggregation.

The above is the detailed content of How to Merge & Aggregate Inbound/Outbound Data with Unique Dates 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template