Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
127 views
in Technique[技术] by (71.8m points)

sql - How to count Distinct value and date less than in the same line

I need to know how many titles and subtitles I have today and how many are over 60 days old. I need help calculating the titles that over 60 days old. Thought of using something like this: count(distinct [Tracking ID1] case when [Date] < DATEADD(DAY, -60, '1/5/2021') but that did work.

I can't use a where statement because it would affect [Titles] and [Subtitles] columns.

enter image description here

select 
    [Line of Business],
    count([Tracking ID]) as [Total # Subtitles],
    count(distinct [Tracking ID1]) as [Total # Titles], 
    count(case when [Date]   < DATEADD(DAY, -60, '1/5/2021') then 1 else 0 end) as [# Subtitles No Action Yet over 60 days], 
    count(distinct [Tracking ID1] case when [Date]   < DATEADD(DAY, -60, '1/5/2021') as [# Titles No Action Yet over 60 days]
    
from table
where 
[Status] like '%active%'
group by [Line of Business]
order by [Line of Business]
question from:https://stackoverflow.com/questions/65602573/how-to-count-distinct-value-and-date-less-than-in-the-same-line

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

use count instead of sum :

select 
    [Line of Business],
    count([Tracking ID]) as [Total # Subtitles],
    count(distinct [Tracking ID1]) as [Total # Titles], 
    COUNT(case when [Date] < DATEADD(DAY, -60, '1/5/2021') then 1 else NULL end) as [# Subtitles No Action Yet over 60 days], 
    COUNT(distinct CASE when [Date] < DATEADD(DAY, -60, '1/5/2021') THEN [Tracking ID1] ELSE NULL END) AS [# Titles No Action Yet over 60 days]    
from table
where 
[Status] like '%active%'
group by [Line of Business]
order by [Line of Business]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...