如何在 SQL 中检索连接表中特定列的不同值并满足特定条件的最旧记录?

huangapple go评论77阅读模式
英文:

How can I retrieve the oldest record from a joined table in SQL with distinct values for a specific column and a certain condition?

问题

I want to get distinct value for column "ID" with condition "Status"=1 and pick the oldest "Date".

有2个表:Table1

ID Code Date
A123 1234 10/9/2018
A123 7890 9/8/2022
B666 9088 1/2/2021
C7633 1048 2/5/2019
A123 5477 8/3/2022

Table2

Code Status
123 1
7890 2
9088 1
1048 1
5477 1

我尝试了以下SQL,但它显示了"ID"=A123的2条记录,"Status=1"。

  1. Select table1.ID, table1.Code, Min(table1.Date),table2.Status
  2. From table1, table2
  3. Where table1.Code=table2.Code
  4. and table2.Status = '1'
  5. Group by table1.ID, table1.Code, table2.Status;

我的期望结果是

ID Code Date Status
A123 1234 10/9/2018 1
B666 9088 1/2/2021 1
C7633 1048 2/5/2019 1
英文:

I want to get distinct vale for column "ID" with condition "Status"=1 and pick the oldest "Date".

There are 2 tables:Table1

  1. | ID | Code | Date |
  2. |--------- | ---------|----------|
  3. |A123 |1234 |10/9/2018 |
  4. |A123 |7890 |9/8/2022 |
  5. |B666 |9088 |1/2/2021 |
  6. |C7633 |1048 |2/5/2019 |
  7. |A123 |5477 |8/3/2022 |

Table2

  1. | Code | Status |
  2. |------- | ---------|
  3. |123 |1 |
  4. |7890 |2 |
  5. |9088 |1 |
  6. |1048 |1 |
  7. |5477 |1 |

I tried below sql, but it show 2 record of "ID" = A123 with "Status=1".

Select table1.ID, table1.Code, Min(table1.Date),table2.Status
From table1, table2
Where table1.Code=table2.Code
and table2.Status = '1'
Group by table1.ID, table1.Code, table2.Status;

My expected result is

ID Code Date Status
A123 1234 10/9/2018 1
B666 9088 1/2/2021 1
C7633 1048 2/5/2019 1

答案1

得分: 0

尝试使用以下SQL查看结果如何,如您期望的那样去重 "ID",然后只需将 "ID" 放在 "Group by" 后面:

  1. Select t1.ID,
  2. Min(t1.Code) min_code,
  3. Min(t1.Date) min_date,
  4. Min(t2.Status) min_status
  5. From table1 t1, table2 t2
  6. Where t1.Code=t2.Code
  7. and t2.Status = '1'
  8. Group by t1.ID;
英文:

Try how the result looks like with below SQL, as you expect distinct "ID", then just put "ID" after "Group by"
<!-- language-all: lang-sql -->
Select t1.ID,
Min(t1.Code) min_code,
Min(t1.Date) min_date,
Min(t2.Status) min_status
From table1 t1, table2 t2
Where t1.Code=t2.Code
and t2.Status = '1'
Group by t1.ID;

huangapple
  • 本文由 发表于 2023年6月6日 14:04:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76411815.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定