想要根据特定条件从两个表中聚合数据(SQL条件连接)

时间:2014-12-09 07:57:30

标签: sql sql-server left-join inner-join

我有两张桌子。

T_MarkPrice

+--------+--------+-------+------------+
| FundID | Symbol | Price | Date       |
+--------+--------+-------+------------+
| 0      | DELL   | 10    | 2014-12-09 |
| 1      | DELL   | 11    | 2014-12-09 |
| 2      | DELL   | 12    | 2014-12-09 |
+--------+--------+-------+------------+

T_Data

+--------+--------+------------+
| FundID | Symbol | Date       |
+--------+--------+------------+
| 1      | DELL   | 2014-12-09 |
| 2      | DELL   | 2014-12-09 |
| 3      | DELL   | 2014-12-09 |
+--------+--------+------------+    

我希望以下格式的两个表中的汇总数据

符号和日期是匹配的必要条件(即T_Data的符号和日期应与T_MarkPrice匹配)。

FundID匹配是一个可选条件,如果T_Data的fundID在T_MarkPrice中可用,则从该行中选择Price,否则从fundID 0匹配日期和符号的行中选择价格。

在这里我们可以看到fundID 3在T_MarkPrice表中不可用,在这种情况下我们必须选择fundID为fundID 0。

输出应该跟随 -

+--------+--------+------------+-------+
| FundID | Symbol | Date       | Price |
+--------+--------+------------+-------+
| 1      | DELL   | 2014-12-09 | 11    |
| 2      | DELL   | 2014-12-09 | 12    |
| 3      | DELL   | 2014-12-09 | 10    |
+--------+--------+------------+-------+

2 个答案:

答案 0 :(得分:1)

将默认价格记录和匹配记录加入您的数据记录。如果该价格存在,则显示匹配价格,否则显示默认价格。

select 
  d.fundid, 
  d.symbol, 
  d.date,
  coalesce(mp.price, mpdef.price) as price
from t_data d
left join t_markprice mpdef on 
  mpdef.symbol = d.symbol and mpdef.date = d.date and mpdef.fundid = 0
left join t_markprice mp on
  mp.symbol = d.symbol and mp.date = d.date and mp.fundid = d.fundid;

答案 1 :(得分:0)

您可以LEFT JOIN这两个表格,并使用COALESCEprice替换为fundId = 0的价格值,以取代不匹配行的SELECT d.FundID, d.Symbol, d.Date, COALESCE(p.price, (SELECT Price FROM T_MarkPrice WHERE FundID = 0)) AS Price FROM T_Data AS d LEFT JOIN T_MarkPrice AS p ON p.FundID = d.FundID AND p.Symbol = d.Symbol AND p.Date = d.Date; 这样:

LEFT JOIN

price会将不匹配的行(例如FundID = 3的行)包含在结果集中,并且null = COALESCE,然后是fundid将使用t_markprice表格中| FUNDID | SYMBOL | DATE | PRICE | |--------|--------|------------|-------| | 1 | DELL | 2014-12-09 | 11 | | 2 | DELL | 2014-12-09 | 12 | | 3 | DELL | 2014-12-09 | 10 | = 0的价格值替换这些不匹配行的可空价格值。

这会给你:

{{1}}