简体   繁体   中英

how to join two tables with one to many relationship

I am using MS SQL Server 2008.

I have two tables.

The first one contains two columns of datetime type StartDate and EndDate and ProductID (int).

The second table contains datetime column SaleDate and ProductID.

What I am trying to accomplish is creation of a table, which would contain ProductID, StartDate, EndDate, and NUMBER OF SALES FOR EACH PRODUCT ID making sure that only sales, that happened between the startDate and the EndDate are included in the resulting table.

I am pulling data from the second table grouping it by ProductID before the attempted join with the first table.

Thanks in advance!

I have not had a chance to try this, but it should work.

select f.ProductID, f.StartDate, f.EndDate, count(*) as Sales
from firstTable f
inner join secondTable s on s.ProductID = f.ProductID
where s.SaleDate between f.StartDate and f.EndDate
group by f.ProductID, f.StartDate, f.EndDate

Pretty basic:

SELECT    a.ProductID, a.StartDate, a.EndDate, COUNT(*) AS Sales
FROM      TAB1 a
LEFT JOIN TAB2 b
ON        a.ProductID = b.ProductID
          AND b.SaleDate >= a.StartDate
          AND b.SaleDate <= a.EndDate
GROUP BY  a.ProductID, a.StartDate, a.EndDate;

The actual query itself to get the information you need is pretty simple:

-- NOTE: if you want to exclude product records for which there
-- are no sales, use an INNER JOIN instead
SELECT p.ProductID, p.StartDate, p.EndDate, COUNT(*) [NumSales]
FROM Products p
LEFT JOIN Sales s 
    ON s.ProductID = p.ProductID
WHERE s.SaleDate BETWEEN p.StartDate AND p.EndDate
GROUP BY p.ProductID, p.StartDate, p.EndDate

However, I would advise against making a separate table out of this information, as it will constantly need to be updated. Instead, if this is a query you think you'll be running often, then I'd suggest turning it into a VIEW :

CREATE VIEW CountSalesView AS
    SELECT p.ProductID, p.StartDate, p.EndDate, COUNT(*) [NumSales]
    FROM Products p
    LEFT JOIN Sales s
        ON s.ProductID = p.ProductID
    WHERE s.SaleDate BETWEEN p.StartDate AND p.EndDate
    GROUP BY p.ProductID, p.StartDate, p.EndDate

From there, you can just query it like a table anytime you need the up-to-date information:

SELECT * 
FROM CountSalesView

Here are some examples of this in action:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM