英文:
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"。
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;
我的期望结果是
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
| 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 |
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;
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" 后面:
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;
英文:
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;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论