我現在的系統有問題。我在我的數據庫上有一個名爲Payment
的表格。 這是表如何使用日期記錄唯一地選擇sql中的月份?
的圖片正如你所看到的,我有利益平衡的相同內容的3月和4月份。 但我希望resultset
值是這樣的:
我只是想只有一個currentIntBal
每個月的詳細信息。順便說一下,我還需要知道如何將日期的varchar
轉換爲日期數據類型本身,因爲字段lastPaymentDate
在varchar
數據類型 我怎麼可能做到這一點?
我現在的系統有問題。我在我的數據庫上有一個名爲Payment
的表格。 這是表如何使用日期記錄唯一地選擇sql中的月份?
的圖片正如你所看到的,我有利益平衡的相同內容的3月和4月份。 但我希望resultset
值是這樣的:
我只是想只有一個currentIntBal
每個月的詳細信息。順便說一下,我還需要知道如何將日期的varchar
轉換爲日期數據類型本身,因爲字段lastPaymentDate
在varchar
數據類型 我怎麼可能做到這一點?
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
在這種情況下,我只是爲每個月的第一次付款。之後更多的信息
編輯:
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從varchar
到date
。我使用了CROSS APPLY
,因此可以多次引用而不重複代碼。
請注意,我也將日期格式更改爲ISO格式,以防止使用不同連接語言的任何問題 - YYYY-MM-DD
可能會給出不一致的結果,但YYYYMMDD
將保持一致。
事情是這樣的:
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)
先生,你能解釋一下什麼是此行'GROUP BY MONTH(lastPaymentDate)+ 12 * YEAR(lastPaymentDate)'對於?謝謝 – 2013-04-21 15:13:18
它創建了一個唯一的月份編號,以便該月的每個日期都具有相同的編號,但是另一個月份中的每個日期都有不同的月份編號。它基本上允許按月從DATETIME值進行分組 – RBarryYoung 2013-04-21 18:03:07