Solved

Find avg day in sql

Posted on 2014-10-02
1
140 Views
Last Modified: 2014-10-12
I want to find avg cid_date. @day_num is going to be 30, 60, 90, 120, 150, 180 days only. It will be from a dropdownlist from asp.net page.
Am I on the right track? To set @day_num to negative looks a bit odd. My result looks fine.

declare @ave_Days as int
DECLARE @day_num int
SET @day_num = -60

set ave_Days = (SELECT COUNT(DISTINCT cid_DATE) / case @day_num                                                              
                                                                    WHEN -60 THEN 2
                                                                    WHEN -90 THEN 3
                                                                    WHEN -120 THEN 4
                                                                    WHEN -150 THEN 5
                                                                    WHEN -180 THEN 6
                                                                    ELSE 1 end
                                    FROM         dbo.mytable
                                    where cid_DATE >= DATEADD(DD, @day_num,getdate()) and cid_DATE < GETDATE())
                                   
print ave_Days
0
Comment
Question by:VBdotnet2005
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 
LVL 69

Accepted Solution

by:
Scott Pletcher earned 500 total points
ID: 40357901
You don't need a CASE statement:

set ave_Days = (SELECT COUNT(DISTINCT cid_DATE) / ABS(@day_num / 30)
                                     FROM         dbo.mytable
                                     where cid_DATE >= DATEADD(DD, @day_num,getdate()) and cid_DATE < GETDATE())
0

Featured Post

Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
Via a live example, show how to setup several different housekeeping processes for a SQL Server.
Viewers will learn how the fundamental information of how to create a table.

707 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