Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
Humate
Posting Yak Master
101 Posts |
Posted - 2007-12-07 : 16:26:06
|
| Hi,I have a table I would like to query, but I can't get my head around the code required.In the first column I have date values, in the second I have a phone number. There are many phone numbers for each date in the table, and it is listed as follows:Date-----------------Number12/07/2007----------4321452612/07/2007----------6567748012/07/2007----------4321452612/08/2007----------1353789412/08/2007----------43214526I would like my query to show each date in the table, with a count of phone number in the second column. Now the tricky part. In the third column I want to count unique numbers, that are not just unique for that day, but not duplicated in the past 7 day date range (for each day). Below is a very small example, mine is with hundreds of rows.Date--------------Count---------Unique12/07/2007----------3-------------212/08/2007----------2-------------1Is this possible? Any help much appreciated.Thanks in advanceHumate |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2007-12-07 : 18:39:37
|
[code]-- Prepare sample dataDECLARE @Sample TABLE ([Date] DATETIME, Number INT)INSERT @SampleSELECT '12/07/2007', 43214526 UNION ALLSELECT '12/07/2007', 65677480 UNION ALLSELECT '12/07/2007', 43214526 UNION ALLSELECT '12/08/2007', 13537894 UNION ALLSELECT '12/08/2007', 43214526-- Show the expected outputSELECT [Date], COUNT(*) AS [Count], COUNT(DISTINCT [Unique]) AS [Unique]FROM ( SELECT s.[Date], CASE WHEN EXISTS (SELECT * FROM @Sample AS t WHERE t.[Date] BETWEEN DATEADD(DAY, -6, s.[Date]) AND DATEADD(DAY, -1, s.[Date]) AND t.Number = s.Number) THEN NULL ELSE s.Number END AS [Unique] FROM @Sample AS s ) AS xGROUP BY [Date]ORDER BY [Date][/code] E 12°55'05.25"N 56°04'39.16" |
 |
|
|
Humate
Posting Yak Master
101 Posts |
Posted - 2007-12-08 : 16:21:38
|
| Wow! Still trying to understand how it works, but I like it. I'll try with my real data. Many thanks Peso! |
 |
|
|
|
|
|
|
|