我确信这已经得到了解答,但对于SQL新手我甚至不确定要查找到什么。
我希望根据唯一的ID和持续时间加入两个表,以返回两个表之间的定价和价格不匹配。这是一个例子:
Table1
PK | Item | Duration | Price
1 | 1 | 10 | 1.99
1 | 1 | 15 | 2.99
Table2
PK | Item | Duration | Price
1 | 1 | 10 | 1.99
1 | 1 | 15 | 3.99
现在我的问题是:
SELECT table1.item,
table1.duration,
table1.pice,
table2.item,
table2.duration,
table2.pice,
FROM table1
INNER JOIN table2 ON table1.item = TABLE 2 item
WHERE table1.duration = table2.duration
这是我的结果的问题。
这是项目和持续时间的匹配,但价格返回错误的价格(它似乎拉动它找到的第一个价格),即它返回:
1 | 10 | 1.99 | 1 | 10 | 1.99
1 | 15 | 1.99 | 1 | 15 | 3.99
我预计与15个持续时间相关的第二个价格将返回2.99。但它返回1.99。
感谢任何帮助或指导。
答案 0 :(得分:0)
我更正了代码中的拼写错误。
select table1.item, table1.duration, table1.price,
table2.item, table2.duration, table2.price
from table1 inner
join table2
on table1.item = table2.item
where table1.duration = table2.duration;
MSAccess提供了您期望的结果,而不是您获得的结果。 考虑仔细检查您的代码。或者,您的SQL实现可能不同。
答案 1 :(得分:0)
以下是TSQL(SQL Server)中用于额外信用的示例。
SELECT
a.[item]
,a.[duration]
,a.[price]
,b.[item]
,b.[duration]
,b.[price]
,a.[price] - b.[price] AS [difference] --Difference between two values.
,CASE WHEN a.[price] - b.[price] <> 0.00 THEN 'NOT MATCHED' --When difference exists.
WHEN a.[price] - b.[price] = 0.00 THEN 'MATCHED' --When difference not exists.
ELSE NULL END AS [matched] --When records not exists.
FROM table1 a
INNER JOIN table2 b ON a.[item] = b.[item]
AND a.[duration] = b.[duration]
结果:
item duration price item duration price Difference Matched
1 10 1.99 1 10 1.99 0.00 MATCHED
1 15 2.99 1 15 3.99 -1.00 NOT MATCHED
然后,如果您只想提取不匹配的记录,那么只需将其添加到底部:
WHERE a.[price] - b.[price] <> 0.00