Reputation: 21
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!
Upvotes: 1
Views: 15458
Reputation: 6866
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
Upvotes: 1
Reputation: 4941
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:
JOIN
: http://sqlfiddle.com/#!3/0b408/2VIEW
: http://sqlfiddle.com/#!3/0758bUpvotes: 0
Reputation: 65
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;
Upvotes: 0