且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检索sql中的表中的值

更新时间:2023-02-23 10:37:01

首先,一些观察结果:

1.付费表中不需要名称字段,因为它已经合法地属于已注册表。它没有标准化 http://www.studytonight.com/dbms/database-normalization.php [ ^ ]

2 .histed_date应该是日期而不是字符串 https://msdn.microsoft.com/en-sg/library/ms186724 .aspx [ ^ ]

接下来,要获得解决方案,您可以使用CTE创建临时表,首先获取上次支付日期的记录,然后在CTE表和付费表之间使用左连接以获得所需结果。参见示例:

First, some observations:
1. There is no need for name field in the Paid table as it already rightfully belongs to Registered table. It is not normalized http://www.studytonight.com/dbms/database-normalization.php[^]
2. paid_date should be date not string https://msdn.microsoft.com/en-sg/library/ms186724.aspx[^]
Next, to get the solution, you can create a temp table using CTE to first get the record of last date paid, then use a left join between the CTE table and the paid table to get the desire outcome. See example:
with cte0 (id, paid_amt, total_paid_amt, last_paid_date)
as 
(
select id, paid_amt, total_paid_amt, paid_date
from paid p1 where paid_date = (
  select max(convert(datetime, paid_date)) from paid p2 where
  p1.id=p2.id
  )
)
select r.id, r.name, paid_amt, total_paid_amt, last_paid_date
from registered r left join cte0 c on r.id=c.id
order by last_paid_date DESC



了解更多:

公用表表达式(CTE) [ ^ ]

SQL连接的可视化表示 [ ^ ]