SELECT CONVERT(NVARCHAR(15), TransDate, 103) AS TransDate,
Isnull(Sum(CONVERT(INT, Amount)), '0') AS Amount
FROM HMS_DiagnosisTransactions
WHERE TransDate BETWEEN '05/01/2015' AND '07/24/2015'
GROUP BY CONVERT(NVARCHAR(15), TransDate, 103)
ORDER BY CONVERT(NVARCHAR(15), TransDate, 103)
它显示为
20/05/2015
20/06/2015
21/05/2015
22/07/2015
但我想要
20/05/2015
21/05/2015
20/06/2015
22/07/2015
答案 0 :(得分:0)
在TransDate
中加Group By
(截断时间),然后您可以在Order By
中使用它:
SELECT CONVERT(NVARCHAR(15), TransDate, 103) AS TransDate,
Isnull(Sum(CONVERT(INT, Amount)), '0') AS Amount
FROM HMS_DiagnosisTransactions
WHERE TransDate BETWEEN '05/01/2015' AND '07/24/2015'
GROUP BY CONVERT(NVARCHAR(15), TransDate, 103), DATEADD(dd, DATEDIFF(dd, 0, TransDate), 0)
ORDER BY DATEADD(dd, DATEDIFF(dd, 0, TransDate), 0)
即使在SQL-Server 2005及更低版本中也是如此。 2008年推出了Date
数据类型,它没有时间部分。然后你只需要把它投到Date
:
SELECT CONVERT(NVARCHAR(15), TransDate, 103) AS TransDate,
Isnull(Sum(CONVERT(INT, Amount)), '0') AS Amount
FROM HMS_DiagnosisTransactions
WHERE TransDate BETWEEN '05/01/2015' AND '07/24/2015'
GROUP BY CONVERT(NVARCHAR(15), TransDate, 103), CAST(TransDate as Date)
ORDER BY CAST(TransDate as Date)
答案 1 :(得分:0)
我假设分组实际上有一个目的,因此您需要使用分组值。将字符串转换回日期:
ORDER BY CONVERT(DATETIME, CONVERT(NVARCHAR(15), TransDate, 103), 103)
答案 2 :(得分:0)
也许您可以将年/月/日值声明为DATEPART
,也可以将它们分组,同时在派生表中执行所有操作。然后只需重新查询它。
SELECT T.TransDate, T.Amount
FROM (
SELECT CONVERT(NVARCHAR(15), TransDate, 103) AS TransDate
, COALESCE(SUM(CONVERT(INT, Amount)), '0') AS Amount
, DATEPART(DD, TransDate) AS DD
, DATEPART(MM, TransDate) AS MM
, DATEPART(YY, TransDate) AS YY
FROM HMS_DiagnosisTransactions
WHERE TransDate BETWEEN '05/01/2015' AND '07/24/2015'
GROUP BY CONVERT(NVARCHAR(15), TransDate, 103)
, DATEPART(DD, TransDate)
, DATEPART(MM, TransDate)
, DATEPART(YY, TransDate)
) AS T
ORDER BY T.YY, T.MM, T.DD;