select CONVERT(VARCHAR(10),accounting.dates,103) as date_of_acc, numbers,
count(accounting.dates) as total from #a
left join accounting on #a.code = accounting.code
where numbers in (5,74)
group by accounting.dates,numbers
order by date_of_acc,numbers;
date_of_acc numbers total
01/07/2019 5 43
01/07/2019 5 53
01/10/2019 5 72
01/10/2019 5 40
01/10/2019 5 44
01/10/2019 5 71
01/10/2019 5 76
01/10/2019 5 77
我需要再次计算"date_of_acc"列,因为他没有特别计算我在一个日期内的所有时间,我需要的是这一个日期"01/07/2019"是一个值,而这个总数需要加在一起。这也适用于其他日期值。
您可以在下面尝试-通过在组中添加CONVERT(VARCHAR(10),accounting.dates,103)
select CONVERT(VARCHAR(10),accounting.dates,103) as date_of_acc, numbers,
count(accounting.dates) as total from #a
left join accounting on #a.code = accounting.code
where numbers in (5,74)
group by CONVERT(VARCHAR(10),accounting.dates,103),numbers
order by date_of_acc,numbers
这:
group by accounting.dates
将为相同的日期但不同的小时、分钟、秒和毫秒生成单独的组。您只需要按日期分组部分:
select convert(varchar(10), cast(accounting.dates as date), 103) as date_of_acc
, numbers
, count(accounting.dates) as total
from #a
left join accounting on #a.code = accounting.code
where numbers in (5,74)
group by cast(accounting.dates as date), numbers
order by date_of_acc, numbers;
如果您将sql更改为这样,您将看到为什么会出现同一日期的多行:
select
accounting.dates as date_of_acc,
numbers,
count(accounting.dates) as total
from #a
left join accounting on #a.code = accounting.code
where numbers in (5,74)
group by accounting.dates,numbers
order by date_of_acc,numbers;
accounting.date会有一些差异(可能像时间(,因为多个日期有相同的日期但不同的时间。分组是在包含时间的情况下完成的,然后在显示日期时去掉时间,这让你想知道为什么同一天的日期会多次出现
这在sql中是允许的(按值分组,然后在显示值之前更改值(,但不是您想要的
要解决此问题,请在GROUP BY中的select AND ALSO中执行CONVERT。这意味着将对转换后的日期进行分组和计数;没有必要"再做一次"——我们只需要确保数据在第一次分组时按照我们想要的方式形成
我不知道我是否正确理解你。在您展示的想要接收的示例中:
date_of_acc numbers total
01/07/2019 10 96
01/10/2019 30 380 (if I calculated correctly)
如果是,您可能应该将查询更改为:
select
CONVERT(VARCHAR(10),accounting.dates,103) as date_of_acc,
SUM(numbers), -- Here changed
count(accounting.dates) as total
from
#a
left join accounting
on #a.code = accounting.code
where
numbers in (5,74)
group by
CONVERT(VARCHAR(10),accounting.dates,103) -- Here another change
order by
date_of_acc -- and last one
如果它没有达到你想要的效果,请详细说明你的问题。