【问题标题】:How to exclude unrelated data when using inner join in SQL Server?在 SQL Server 中使用内部联接时如何排除不相关的数据?
【发布时间】:2020-06-09 12:43:34
【问题描述】:

我手头有 2 张桌子。 Table_A 包含销售日期、水果类型、销售数量和总价。 Table_B为不同时间段不同水果的单价。

表_A:

Sales_Date    Fruit     Quantity  Total_Price
20200515      Apple        2          4 
20200601      Apple        4          10
20200601      Banana       4          7.2
20200606      Orange       6          7.8

表 B:

Fruit      Valid_Price_From     Valid_Price_To     Unit_Price 
Apple         20200301            20200531          2.0
Banana        20200301            20200531          1.5
Orange        20200301            20200531          1.0
Apple         20200601            20200831          2.5
Banana        20200601            20200831          1.8
Orange        20200601            20200831          1.3

我需要形成一个表格C,将销售相关信息与在该期间内有效的单价与此格式相结合。

表 C:

Sales_Date      Fruit      Quantity     Unit_Price    Total_Price
20200515        Apple         2             2             4 
20200601        Apple         4            2.5            10
20200601        Banana        4            1.8            7.2
20200606        Orange        6            1.3            7.8

我使用的第一个查询是

select A.Sales_Date, A.Fruit, A.Quantity, B.Unit_Price, A.Total Price
from table_A A 
inner join
table_B B on A.Fruit=B.Fruit

但是在加入这 2 个表时出现错误。

我猜这是因为每种水果有两种类型的Unit Price(不同时期有效)。然后,我尝试将Sales_DateValid_Price_FromValid_Price_To 进行比较

我使用的第二个查询是:

select A.Sales_Date, A.Fruit, A.Quantity, B.Unit_Price, A.Total Price
from table_A A 
inner join
table_B B on A.Fruit=B.Fruit
where A.Sales_Date > B.Valid_Price_From and A.Sales_Date < B.Valid_Price_To

但它也不能正常工作。

我可以知道我应该如何构造我的内部连接查询以获得所需的输出,如表 C 所示?

【问题讨论】:

  • 您的第二个查询看起来不错(您只需要&gt;= 而不是&gt;&lt;= 而不是&lt;)。什么是无法正常工作
  • 你的问题标签合适吗?我没有看到任何链接服务器引用,也不清楚 MySQL 和 Microsoft SQL Server 是否/如何相关。
  • @GMB 其实我有两种销售价格计算方法,第一种是我提到的那种,第二种是使用另一种计算方法,而不像第一种方法那样使用任何定期价格。如果我使用比较查询,我将无法获得所需的输出。它将排除使用第二种方法获取总销售价格的销售,因为 Valid_Price_To 和 Valid_Price_From 使用第二种方法的销售为 NULL

标签: sql sql-server tsql


【解决方案1】:

您的查询中的日期比较不正确:

select A.Sales_Date, A.Fruit, A.Quantity, B.Unit_Price, A.Total_Price
from table_A A inner join
     table_B B
     on A.Fruit = B.Fruit and
        A.Sales_Date >= B.Valid_Price_From and 
        A.Sales_Date <= B.Valid_Price_To;

换句话说,您没有包含开始日期和结束日期,但您的数据模型表明您确实希望包含它们。

如果您担心过滤掉不匹配的行,那么您可能需要修复数据。但是您可以继续使用left join 而不是inner join

【讨论】:

  • 不,我需要比较才能获得正确的单价,但如果销售日期未包含在表 B 中,它将消除销售。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-24
  • 2011-12-23
  • 2012-01-28
  • 1970-01-01
  • 1970-01-01
  • 2011-09-18
  • 2012-11-03
相关资源
最近更新 更多