繁体   English   中英

如何以一对多关系连接两个表

[英]how to join two tables with one to many relationship

我正在使用MS SQL Server 2008。

我有两张桌子。

第一个包含两列日期时间类型StartDate和EndDate和ProductID(int)。

第二个表包含datetime列SaleDate和ProductID。

我要完成的工作是创建一个表,该表将包含ProductID,StartDate,EndDate和每个产品ID的销售数量,以确保仅将发生在startDate和EndDate之间的销售额包含在结果表中。

在尝试与第一个表联接之前,我正在从第二个表中按ProductID将数据分组。

提前致谢!

我没有机会尝试这个,但是应该可以。

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

很基本的:

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;

获取所需信息的实际查询本身非常简单:

-- 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

但是,我建议不要从此信息中创建单独的表,因为将需要不断对其进行更新。 相反,如果您认为这是一个经常运行的查询,则建议将其转换为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

从那里,您可以在需要最新信息时随时像表一样查询它:

SELECT * 
FROM CountSalesView

以下是一些实际的例子:

  • 提琴JOINhttp ://sqlfiddle.com/#!3/ JOIN /2
  • 小提琴VIEWhttp ://sqlfiddle.com/#!3/0758b

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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