1

我当前的系统有问题。我的数据库中有一个名为的表Payment。这是桌子的图片

在此处输入图像描述

如您所见,我对 3 月和 4 月的利息余额有相同的详细信息。但我希望resultset值是这样的:

在此处输入图像描述

我只想要currentIntBal每个月的一个细节。顺便说一句,我还需要知道如何将日期转换varchar为日期数据类型本身,因为该字段lastPaymentDatevarchar数据类型我怎么可能做到呢?

4

2 回答 2

0
with monthlyPayments as
(
  select *
    , rownum = row_number() over (partition by year(lastPaymentDate), month(lastPaymentDate) order by lastPaymentDate)
  from payments
)
select lastPaymentDate
  , currentIntBal
from monthlyPayments
where rownum = 1

SQL Fiddle 与演示

在这种情况下,我只是每月支付第一笔款项。

在附加信息后编辑:

with monthlyPayments as
(
  select *
    , rownum = row_number() over (partition by year(convertedDate), month(convertedDate) order by convertedDate)
  from payments p
    cross apply (select convertedDate = cast(replace(lastPaymentDate,'-','') as date)) c
)
select lastPaymentDate = convertedDate
  , currentIntBal
from monthlyPayments
where rownum = 1

在上面的新查询中,我将lastPaymentDate从更改varchardate。我使用了 aCROSS APPLY所以它可以被多次引用而无需重复代码。

请注意,我还将日期格式更改为 ISO 格式,以防止不同连接语言出现任何问题 -YYYY-MM-DD可能会给出不一致的结果,但YYYYMMDD会保持一致。

SQL Fiddle 与演示

于 2013-04-21T15:02:11.147 回答
0

像这样的东西:

SELECT MIN(lastPaymentDate) As lastPaymentDate, currentInBal
FROM   yourTable
GROUP BY currentInBal, MONTH(lastPaymentDate)+12*YEAR(lastPaymentDate)

另一种略有不同的方式:

SELECT MIN(lastPaymentDate) As lastPaymentDate, 
    MIN(currentInBal) As currentInBal
FROM   yourTable
GROUP BY MONTH(lastPaymentDate)+12*YEAR(lastPaymentDate)
于 2013-04-21T15:02:39.907 回答