我在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才能生成这些结果?
答案 0 :(得分:42)
我喜欢(MS SQL)中的这种方法:
SELECT
Convert(char(8), LogDate, 112),
count(distinct RefundId)
FROM RefundProcessing
GROUP BY Convert(char(8), LogDate, 112)
答案 1 :(得分:17)
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(DISTINCT refundId)
答案 2 :(得分:6)
您使用的是哪种数据库供应商?无论它是什么,用以下相应的构造替换下面的“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))
答案 3 :(得分: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”
答案 4 :(得分: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)
答案 5 :(得分:0)
Select count(*), LogDate, refundid from RefundProcessLog
where refundid is not null
group by LogDate, refundid
编辑:
如果您不希望退款
,请删除RefundID答案 6 :(得分: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])