Solved

Mssql SQL query

Posted on 2016-11-29
14
20 Views
Last Modified: 2016-11-29
Guys,

I have a query below that works to get for me daily count of daily data,  but how about if I want to get this query only to give me sums of monthly data ?  how the query data looks like ?


select [InsertedDate],count ([InsertedDate]) as EventCount
from ArchiveLoginsLogs
where [InsertedDate] >='2010-01-01' and [InsertedDate]
<'2016-11-29'
group by [InsertedDate]
Order by [InsertedDate] asc
0
Comment
Question by:motioneye
  • 6
  • 3
  • 2
  • +3
14 Comments
 
LVL 45

Assisted Solution

by:Vitor Montalvão
Vitor Montalvão earned 50 total points
Comment Utility
Use the YEAR and MONTH function:
select [InsertedDate],year(InsertedDate) as 'Year', month(InsertedDate) as 'Month', count ([InsertedDate]) as EventCount
 from ArchiveLoginsLogs
 where [InsertedDate] >='2010-01-01' and [InsertedDate] <'2016-11-29' 
 group by [InsertedDate]],year(InsertedDate), month(InsertedDate)  
 Order by [InsertedDate] asc 

Open in new window

0
 
LVL 16

Expert Comment

by:Pawan Kumar Khowal
Comment Utility
Try..

SELECT * , COUNT(*) OVER (PARTITION BY YEAR([InsertedDate]),MONTH([InsertedDate]))  EventMonthCount
from ArchiveLoginsLogs
where [InsertedDate] >='2010-01-01' and [InsertedDate] <'2016-11-29' 

Open in new window


If you want sum of any column use below- SUM(YourColumnName)

SELECT * , SUM(YourColumnName) OVER (PARTITION BY YEAR([InsertedDate]),MONTH([InsertedDate]))  EventMonthCount
from ArchiveLoginsLogs
where [InsertedDate] >='2010-01-01' and [InsertedDate] <'2016-11-29' 

Open in new window


Hope it helps !!
0
 
LVL 49

Expert Comment

by:Ryan Chong
Comment Utility
for Vitor's comment, you no need to select [InsertedDate] ... and  group by [InsertedDate],

hence:

select year(InsertedDate) as 'Year', month(InsertedDate) as 'Month', count ([InsertedDate]) as EventCount
 from ArchiveLoginsLogs
 where [InsertedDate] >='2010-01-01' and [InsertedDate] <'2016-11-29' 
 group by year(InsertedDate), month(InsertedDate)  
 Order by 1,2

Open in new window

0
 
LVL 16

Assisted Solution

by:Pawan Kumar Khowal
Pawan Kumar Khowal earned 325 total points
Comment Utility
Or you can use this..

select YEAR([InsertedDate]) YearInsrt ,MONTH([InsertedDate]) MonthInst , COUNT(*) CountByYearMonth
from ArchiveLoginsLogs
where [InsertedDate] >='2010-01-01' and [InsertedDate] <'2016-11-29' 
group by YEAR([InsertedDate]),MONTH([InsertedDate])
Order by YEAR([InsertedDate]),MONTH([InsertedDate])

Open in new window


Hope it helps !!
0
 
LVL 45

Expert Comment

by:Vitor Montalvão
Comment Utility
for Vitor's comment, you no need to select  [InsertedDate] ... and  group by [InsertedDate],
True. I just copied the code and forgot to update that part. Nice catch, Ryan.
0
 

Author Comment

by:motioneye
Comment Utility
Guys,
Both query did not  return me the data I want, the query below provide me with counts of data daily, but how do I sums this  EventCount so that I can present the count monthly ? so the output that I'm looking for shoud be like thsi .

InsertedDate      EventCount
2016-01-01      4216
2016-02-02      1925
2016-03-03      1854
2016-04-04      4606

Or can be like this

InsertedDate      EventCount
2016-01-01 - 2016-01-31      4216
2016-02-02  - 2016-02-29      1925
2016-03-03 - 2016-03-30      1854
2016-04-04 - 2016-03-31    4606




select [InsertedDate],count ([InsertedDate]) as EventCount
from ArchiveLoginsLogs
where [InsertedDate] >='2010-01-01' and [InsertedDate]
<'2016-11-29'
group by [InsertedDate]
Order by [InsertedDate] asc

short output from the query

InsertedDate      EventCount
2016-01-01      4216
2016-01-02      1925
2016-01-03      1854
2016-01-04      4606
0
 
LVL 16

Expert Comment

by:Pawan Kumar Khowal
Comment Utility
Try..
SELECT DISTINCT DATEFROMPARTS(YEAR([InsertedDate]),MONTH([InsertedDate]),'01') InsertedDate , COUNT(*) OVER (PARTITION BY YEAR([InsertedDate]),MONTH([InsertedDate]))  EventCount
from ArchiveLoginsLogs
where [InsertedDate] >='2010-01-01' and [InsertedDate] <'2016-11-29' 

Open in new window

0
Get up to 2TB FREE CLOUD per backup license!

An exclusive Black Friday offer just for Expert Exchange audience! Buy any of our top-rated backup solutions & get up to 2TB free cloud per system! Perform local & cloud backup in the same step, and restore instantly—anytime, anywhere. Grab this deal now before it disappears!

 
LVL 16

Expert Comment

by:Pawan Kumar Khowal
Comment Utility
Or this...

SELECT DISTINCT CONCAT(  DATEFROMPARTS(YEAR([InsertedDate]),MONTH([InsertedDate]),'01') , ' - ' ,
EOMONTH(DATEFROMPARTS(YEAR([InsertedDate]),MONTH([InsertedDate]),'01')) )InsertedDate
,COUNT(*) OVER (PARTITION BY YEAR([InsertedDate]),MONTH([InsertedDate]))  EventCount
from ArchiveLoginsLogs
where [InsertedDate] >='2010-01-01' and [InsertedDate] <'2016-11-29' 

Open in new window

0
 
LVL 16

Accepted Solution

by:
Pawan Kumar Khowal earned 325 total points
Comment Utility
Or...use can use from below--

1.........

select CONCAT(  DATEFROMPARTS( YEAR([InsertedDate]) ,MONTH([InsertedDate]) , '01' ) , ' - ' ,
EOMONTH(DATEFROMPARTS( YEAR([InsertedDate]) ,MONTH([InsertedDate]) , '01' )) ) InsertedDate
, COUNT(*) CountByYearMonth
from ArchiveLoginsLogs
where [InsertedDate] >='2010-01-01' and [InsertedDate] <'2016-11-29' 
group by YEAR([InsertedDate]),MONTH([InsertedDate])
Order by YEAR([InsertedDate]),MONTH([InsertedDate])

Open in new window


2..............

select DATEFROMPARTS( YEAR([InsertedDate]) ,MONTH([InsertedDate]) , '01' ) InsertedDate
, COUNT(*) CountByYearMonth
from ArchiveLoginsLogs
where [InsertedDate] >='2010-01-01' and [InsertedDate] <'2016-11-29' 
group by YEAR([InsertedDate]),MONTH([InsertedDate])
Order by YEAR([InsertedDate]),MONTH([InsertedDate])

Open in new window

0
 
LVL 45

Expert Comment

by:Vitor Montalvão
Comment Utility
The periods shouldn't start all at day one? Why Feb starts at day two and March at day three and so on?
InsertedDate      EventCount
 2016-01-01 - 2016-01-31      4216
 2016-02-02  - 2016-02-29      1925
 2016-03-03 - 2016-03-30      1854
 2016-04-04 - 2016-03-31    4606

Also, if you want a SUM why the above example isn't a SUM but the values from January days?
InsertedDate      EventCount
 2016-01-01      4216
 2016-01-02      1925
 2016-01-03      1854
 2016-01-04      4606
0
 
LVL 16

Assisted Solution

by:Pawan Kumar Khowal
Pawan Kumar Khowal earned 325 total points
Comment Utility
If you are using SQL 2008..

1.........

select CAST(  CAST(CAST(YEAR([InsertedDate]) AS VARCHAR(4)) + '/' + LEFT('0'+CAST(MONTH([InsertedDate]) AS VARCHAR(2)),2) + '/' + '01' AS DATE) AS VARCHAR(15)) , ' - ' ,
CAST( EOMONTH(CAST(CAST(YEAR([InsertedDate]) AS VARCHAR(4)) + '/' + LEFT('0'+CAST(MONTH([InsertedDate]) AS VARCHAR(2)),2) + '/' + '01' AS DATE) ) AS VARCHAR(15))
InsertedDate
, COUNT(*) CountByYearMonth
from ArchiveLoginsLogs
where [InsertedDate] >='2010-01-01' and [InsertedDate] <'2016-11-29' 
group by YEAR([InsertedDate]),MONTH([InsertedDate])
Order by YEAR([InsertedDate]),MONTH([InsertedDate])

Open in new window


The output will looks like.. <<Month will increase , day will be the first day of the month and the last day of the month everytime, I think thats what you wanted.>>

InsertedDate                        EventCount
2016-01-01 - 2016-01-31       4216
2016-02-01  - 2016-02-29      1925
2016-03-01 - 2016-03-30       1854
2016-04-01 - 2016-03-31       4606

2..............

select CAST(CAST(YEAR([InsertedDate]) AS VARCHAR(4)) + '/' + LEFT('0'+CAST(MONTH([InsertedDate]) AS VARCHAR(2)),2) + '/' + '01' AS DATE) [InsertedDate]
, COUNT(*) CountByYearMonth
from ArchiveLoginsLogs
where [InsertedDate] >='2010-01-01' and [InsertedDate] <'2016-11-29' 
group by YEAR([InsertedDate]),MONTH([InsertedDate])
Order by YEAR([InsertedDate]),MONTH([InsertedDate])

Open in new window


The output will looks like.. <<Month will increase , day will be the first day of the month everytime, I think thats what you wanted.>>

InsertedDate      EventCount
 2016-01-01      4216
 2016-02-01      1925
 2016-03-01      1854
 2016-04-01      4606

Hope it helps !!
0
 
LVL 48

Assisted Solution

by:PortletPaul
PortletPaul earned 125 total points
Comment Utility
To include a monthly total you could use "group by rollup" although the labels for the subtotals gets a bit tricky in my opinion
try this:
select
          coalesce(InsertedDate, left(lag(InsertedDate,1) over(order by (select 1)),7),'total') InsertedDate
        , event_count
from (
        select
              convert(varchar(10),InsertedDate,120) InsertedDate
            , count(*) event_count
        from ArchiveLoginsLogs
        where [InsertedDate] >='2010-01-01' and [InsertedDate] <'2016-11-29' 
        group by rollup ( datepart(mm,InsertedDate), InsertedDate ) 
    ) g
;

Open in new window

a result would look something like this:
+----+--------------+-------------+
|    | InsertedDate | event_count |
+----+--------------+-------------+
|  1 | 2016-01-01   |           2 |
|  2 | 2016-01-11   |           1 |
|  3 | 2016-01-21   |           1 |
|  4 | 2016-01      |           4 |
|  5 | 2016-02-02   |           1 |
|  6 | 2016-02-12   |           2 |
|  7 | 2016-02-22   |           1 |
|  8 | 2016-02      |           4 |
|  9 | 2016-03-03   |           2 |
| 10 | 2016-03-13   |           1 |
| 11 | 2016-03-23   |           1 |
| 12 | 2016-03      |           4 |
| 13 | 2016-04-04   |           1 |
| 14 | 2016-04-14   |           1 |
| 15 | 2016-04-24   |           1 |
| 16 | 2016-04      |           3 |
| 17 | total        |          15 |
+----+--------------+-------------+

Open in new window

0
 
LVL 69

Expert Comment

by:ScottPletcher
Comment Utility
SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, [InsertedDate]), 0) AS [InsertedMonth],
    COUNT(*) AS EventCount
FROM ArchiveLoginsLogs
WHERE [InsertedDate] >='2010-01-01' AND
              [InsertedDate] < DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)
GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, [InsertedDate]), 0)
ORDER BY DATEADD(MONTH, DATEDIFF(MONTH, 0, [InsertedDate]), 0)


Don't use string conversion in any way (unless absolutely unavoidable), because it will vastly slow down (and complicate) the query.

The general format above could be used for yearly totals also, for example:

SELECT DATEADD(YEAR, DATEDIFF(YEAR, 0, [InsertedDate]), 0) AS [InsertedYear],
...

Thus, this technique is not only very efficient but it's also consistent for different date granularities.  For example, if you had a full datetime and wanted hourly totals:
SELECT DATEADD(HOUR, DATEDIFF(HOUR, 0, [InsertedDate]), 0) AS [InsertedHour],
...
0
 

Author Closing Comment

by:motioneye
Comment Utility
Thanks guys,I managed it with your guys help
0

Featured Post

Backup Your Microsoft Windows Server®

Backup all your Microsoft Windows Server – on-premises, in remote locations, in private and hybrid clouds. Your entire Windows Server will be backed up in one easy step with patented, block-level disk imaging. We achieve RTOs (recovery time objectives) as low as 15 seconds.

Join & Write a Comment

Everyone has problem when going to load data into Data warehouse (EDW). They all need to confirm that data quality is good but they don't no how to proceed. Microsoft has provided new task within SSIS 2008 called "Data Profiler Task". It solve th…
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now