21

我在 SQL Server 中有一个如下所示的日志表:

CREATE TABLE [dbo].[RefundProcessLog](
 [LogId] [bigint] IDENTITY(1,1) NOT NULL,
 [LogDate] [datetime] NOT NULL,
 [LogType] [varchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
 [RefundId] [int] NULL,
 [RefundTypeId] [smallint] NULL,
 [LogMessage] [varchar](1000) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
 [LoggedBy] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
 CONSTRAINT [PK_RefundProcessLog] PRIMARY KEY CLUSTERED 
(
 [LogId] ASC
) ON [PRIMARY]
) ON [PRIMARY]

GO

我想要的是一个结果列表,它代表每天处理了多少不同的退款,丢弃任何 NULL。

我需要编写什么 SQL 才能产生这些结果?

4

7 回答 7

49

我喜欢(MS SQL)中的这种方法:

SELECT 
  Convert(char(8), LogDate, 112),
  count(distinct RefundId)
FROM RefundProcessing
GROUP BY Convert(char(8), LogDate, 112)
于 2009-09-22T16:52:54.870 回答
21
select cast(LogDate as date) as LogDate, count(refundId) as refundCount
from yourTable
group by cast(LogDate as date)

根据您使用的 SQL 方言,您可能需要将 CAST 更改为其他内容。该表达式应将 LogDate 转换为仅日期值。

另外,如果您说“不同的refundId”,因为您可能只想计算一次refundId的重复值,请使用count(DISTINCTrefundId)

于 2009-09-21T15:26:24.463 回答
7

您使用的是哪个数据库供应商?不管是哪一种,用适当的结构替换下面的“DateOnly(LogDate)”,以从 logdate 列值中提取日期部分(去掉时间),然后试试这个:

Select [DateOnly(LogDate)], Count Distinct RefundId
From RefundProcessLog
Group By [DateOnly(LogDate)]

例如,在 Sql server 中,适当的构造将是:

Select DateAdd(day, 0, DateDiff(day, 0, LogDate)), Count(Distinct RefundId)
From RefundProcessLog
Group By DateAdd(day, 0, DateDiff(day, 0, LogDate))
于 2009-09-21T15:25:10.550 回答
1
SELECT COUNT(RefundId), DateOnly(LogDate) LoggingDate
FROM RefundProcessLog
GROUP BY DateOnly(LogDate)

“DateOnly”特定于您的 SQL 数据库,您没有指定它。

对于 SQL Server,您可以将 DateAdd(dd,0, DateDiff(dd,0,LogDate)) 用于“DateOnly”

于 2009-09-21T15:25:14.477 回答
1

SQL Server 2008 引入了date数据类型,使以下操作成为可能:

select convert(date, LogDate),
      ,count(refundid) AS 'refunds'
  from RefundProcessing
group by convert(date,LogDate)
order by convert(date,LogDate)
于 2020-01-17T15:03:46.083 回答
0

在 SqlServer 中,它将类似于:

select datepart(YEAR, [LogDate]), datepart(MONTH, [LogDate]), datepart(DAY, [LogDate]), count(refundid) as [Count]
from [RefundProcessing]
group by datepart(YEAR, [LogDate]), datepart(MONTH, [LogDate]), datepart(DAY, [LogDate])
于 2009-09-21T15:24:28.103 回答
-1
Select count(*), LogDate, refundid from RefundProcessLog
where refundid is not null
group by LogDate, refundid

编辑:

如果您不希望它被退款分解,或者删除 RefundID

于 2009-09-21T15:23:28.037 回答