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.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Date field

Author  Topic 

satya068
Posting Yak Master

233 Posts

Posted - 2014-12-04 : 04:22:37
Hi,

I would like to add a date field to my sql query which i dont want to groupby the date field,can i know where should i include that in my below script.

select COUNT(*) AS Page_Views, [Speciality Name], [Sub Speciality Name], [Page Name]
from
(
SELECT s.[Speciality Name], ss.[Sub Speciality Name], pa.[Page Name]
FROM [Parent Site] AS p INNER JOIN
Speciality AS s ON s.[Parent Site] = p.[Site Key] LEFT OUTER JOIN
[Sub Speciality] AS ss ON s.[Speciality Key] = ss.Speciality LEFT OUTER JOIN
Pages AS pa ON pa.[Sub Speciality] = ss.[Sub Speciality Key] LEFT OUTER JOIN
[Page Views] AS pv ON pv.[Page key] = pa.[Page Key]
WHERE (pv.Date IS NOT NULL)
) a
GROUP BY [Speciality Name], [Sub Speciality Name],[Page Name]
order by 1 desc

Thanks

gbritton
Master Smack Fu Yak Hacker

2780 Posts

Posted - 2014-12-04 : 09:28:33
I assume that you mean the column pv.Date in the subquery. If you want to select it in the main query, you have two choices:

1. add it to the group by
2. aggregate it somehow.

Here is your query with the date field aggregated with the MAX() function:


SELECT COUNT(*)AS Page_Views
, [Speciality Name]
, [Sub Speciality Name]
, [Page Name]
FROM(
SELECT s.[Speciality Name]
, ss.[Sub Speciality Name]
, pa.[Page Name]
, max(a.Date)

FROM [Parent Site] AS p
INNER JOIN Speciality AS s
ON s.[Parent Site] = p.[Site Key]
LEFT OUTER JOIN [Sub Speciality] AS ss
ON s.[Speciality Key] = ss.Speciality
LEFT OUTER JOIN Pages AS pa
ON pa.[Sub Speciality] = ss.[Sub Speciality Key]
LEFT OUTER JOIN [Page Views] AS pv
ON pv.[Page key] = pa.[Page Key]
WHERE pv.Date IS NOT NULL)a
GROUP BY [Speciality Name]
, [Sub Speciality Name]
, [Page Name]
ORDER BY 1 DESC;
Go to Top of Page
   

- Advertisement -