有什么办法可以对同一日期列进行两次计数?

时间:2019-11-15 07:13:51

标签: sql sql-server group-by

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”为一个值,并且总和必须为一。 这也适用于其他日期值。

4 个答案:

答案 0 :(得分:3)

您可以在下面尝试-将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

答案 1 :(得分:2)

此:

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;

答案 2 :(得分:2)

如果您将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.dates会有一些差异(例如某个时间),其中多个日期具有相同的日期而不同的时间。分组是在包含时间的情况下进行的,然后在显示日期时剥离时间,您想知道为什么同一天的日期会显示多次

这在sql中是允许的(对值进行分组,然后在显示值之前更改它),但不是您想要的

要修复此问题,请在GROUP BY的select AND ALSO中同时执行CONVERT。这意味着将对转换后的日期进行分组和计数;无需“再做一次”-我们只需要确保数据按我们希望的第一次分组的方式进行整形

答案 3 :(得分:0)

我不知道我是否正确理解你。在您显示的示例中,您希望收到:

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

如果它没有满足您的要求,请详细说明您的问题。