我正在努力获取这两个查询:
SELECT min(to_date(nullif(mydatetext,''), 'DD.MM.YYYY')) AS dmin,
max(to_date(nullif(mydatetxt,''), 'DD.MM.YYYY')) AS dmax
FROM mytable
和
SELECT count(*)
FROM mytable
WHERE
to_date(nullif(mydatetxt,'')) 'ERROR HERE
BETWEEN
max(to_date(nullif(mydatetxt,''), 'DD.MM.YYYY'))
AND
min(to_date(nullif(mydatetxt,''), 'DD.MM.YYYY'))
在单个中,因此我可以将结果读取为最小日期、最大日期、介于最小和最大日期之间(包括最小和最大日期)的日期计数。但这里有几个问题。
第二个查询不按预期工作或根本不工作,因此必须改进。如果这两个查询可以写在单个查询(?)中,我可以使用第一部分的 dmin 和 dmax 变量作为第二部分的变量吗?像这样:
SELECT count(*)
FROM mytable
WHERE
to_date(nullif(mydatetxt,'')) 'ERROR HERE
BETWEEN
dmin
AND
dmax
请帮助最终解决这种情况。
可操作的代码:
Using cmd As New NpgsqlCommand("SELECT my_id, mydate FROM " & mytable, conn)
Using dr As NpgsqlDataReader = cmd.ExecuteReader()
While dr.Read()
mydate = CStr(dr(1))
If IsDate(mydate) Then
Dim dat As Date = CDate(mydate.Substring(6, 4) & "/" & mydate.Substring(3, 2) & "/" & mydate.Substring(0, 2))
If dat < mindate Or mindate = Nothing Then
mindate = dat
End If
If dat > maxddate Or maxdate = Nothing Then
maxdate = dat
End If
count += 1
End If
End While
End Using
End Using
解决方案:这是最后一个非常快速的改进版本,Ervin 好心地给出:
Using cmd As New NpgsqlCommand( _
"WITH base AS (" & _
" SELECT TO_DATE(datum, 'DD.MM.YYYY') AS the_date " & _
" FROM " & myKalkTable & " " & _
" WHERE datum <> '') " & _
" SELECT MIN(the_date) AS dmin, " & _
" MAX(the_date) AS dmax, " & _
" COUNT(*) AS ct_incl, " & _
" (SELECT COUNT(*) " & _
" FROM base b1 " & _
" WHERE(b1.the_date < max(b.the_date)) " & _
" AND b1.the_date > min(b.the_date)) " & _
" AS ct_excl " & _
" FROM base b", conn)
Using dr As NpgsqlDataReader = cmd.ExecuteReader()
While dr.Read()
mindate = CType(CDate(CStr(dr(0))), Date)
maxdate = CType(CDate(CStr(dr(1))), Date)
count = CInt(dr(2))
End While
End Using
End Using