最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

sql - Query to return fixed rows even if matching rows missing in join - Stack Overflow

programmeradmin4浏览0评论

In SQL Server I have Table1 with rows as follows

Col 1 Col 2
A Andy
B Becky
C Carol

In SQL Server I have Table1 with rows as follows

Col 1 Col 2
A Andy
B Becky
C Carol

In Table2 I have following rows

Col 1 Col 2 Col 3
A Low 3
A Medium 2
A High 5
B High 7
C Low 1
C High 12

Using a join I want to out rows for all 3 values (Low, Medium, High) even if its missing from Table2

So essentially I want to get

Col 1 Col 2 Col 3
A Low 3
A Medium 2
A High 5
B Low NULL
B Medium NULL
B High 7
C Low 1
C High 12
C Medium NULL

How can I write my join to return fixed rows even when missing in Table2?

Share Improve this question edited yesterday Dale K 27.3k15 gold badges57 silver badges83 bronze badges asked yesterday JakeUTJakeUT 5371 gold badge13 silver badges26 bronze badges 3
  • 1 What have you tried? Where did you get stuck? hint "Cross join". – Dale K Commented yesterday
  • Although where should the list of Low, Medium, High come from? The only way to can be sure to show one of each is if you can build a list of all options somehow. Hopefully that enum us stored in another database table. – Dale K Commented yesterday
  • Thanks! didnt think of the Cross join :) – JakeUT Commented yesterday
Add a comment  | 

1 Answer 1

Reset to default 1

You can cross-join Table1 with a constructed table of those three values (or a real table if you have one), then left join Table2.

SELECT
  t1.Col1,
  v.Col2,
  t2.Col3
FROM Table1 t1
CROSS JOIN (VALUES
  ('Low'),
  ('Medium'),
  ('High')
) v(Col2)
LEFT JOIN Table2 t2
  ON t2.Col1 = t1.Col1
  AND t2.Col2 = v.Col2;

db<>fiddle

发布评论

评论列表(0)

  1. 暂无评论