简体   繁体   中英

T-SQL Convert DateTime and Count entries for each date

I am lost on how to solve what I believe should be a simple query.

I want to count the number of entries for each date in a table. The column DateCreated is in DateTime format. I can convert the datetime to date using

convert(VARCHAR, JobApps.DateCreated, 2) as Date

but with COUNT(ID) as Qty I get a count of 1 with multiple "Date" rows.

Here is the SQL query I am using.

SELECT  
    convert(VARCHAR, DateCreated, 2) as Date, COUNT(CompanyName) as Qty
FROM Apps  
GROUP BY DateCreated
ORDER BY DateCreated DESC

This is the results I get.

Date       Qty
------------------
13.05.29   1
13.05.29   1
13.05.29   1
13.05.29   1
13.05.29   1
13.05.28   1
13.05.28   1
13.05.27   1
13.05.27   1

etc...

What I wanting is a result like this...

Date       Qty
-----------------
13.05.29   5
13.05.28   2
13.05.27   2

etc...

Just gotta change your GROUP BY to use the actual value you want:

SELECT convert(VARCHAR, DateCreated, 2) as Date, COUNT(1) as Qty
FROM Apps
GROUP BY convert(VARCHAR, DateCreated, 2)
ORDER BY Date DESC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM