根据日期和小时从同一张表中减去两行

时间:2018-11-26 13:23:59

标签: sql sql-server azure-sql-database subtraction

我想加入两个表。

表A

  Date     | Hour | Direction | Qty 
2018-11-20    1      DE/UK       2 
2018-11-20    2      DE/UK       6 

表B

   Date    | Hour | Area  | Price
2018-11-20    1      DE       5 
2018-11-20    2      DE       4 
2018-11-20    1      UK       3 
2018-11-20    2      UK       9 

我想这样加入他们:

表C

 Date     | Hour | Direction | Qty | AreaFrom | AreaTo | PriceFrom | PriceTo | Profit
2018-11-20    1      DE/UK       2      DE       UK         5           3      3-5 = -2
2018-11-20    2      DE/UK       6      DE       UK         4           9        5

我已经尝试过CROSS Join和其他类型的联接,但是无法使其正常工作。

到目前为止,我研究过的其他相关问题:

SQL subtract two rows based on date and another column

Selecting two rows from the same table

1 个答案:

答案 0 :(得分:1)

它可能不像亚当所讲的那么复杂。如果TableA具有“ directionFrom”和“ directionTo”列,则您可能自己解决了这一问题。因此,将方向字段分为两列:

SELECT 
  a.[Date], a.[Hour], a.Direction, a.Qty, 
  f.Area as AreaFrom, t.Area as AreaTo, 
  f.Price as priceFrom, t.Price as PriceTo, 
  t.Price-f.Price as profit
FROM 
  TableA a
  INNER JOIN TableB f 
  ON 
    a.[Date] = f.[Date] and 
    a.Hour = b.[Hour] and
    LEFT(a.Direction, 2) = f.Area --take the left two as the area from
  INNER JOIN TableB t 
  ON 
    a.[Date] = t.[Date] and 
    a.Hour = t.[Hour] and
    RIGHT(a.Direction, 2) = t.Area --take the right two as the area to

如果您的区域包含两个以上的字母代码,则必须使用/的CHARINDEX代替