Quantcast
Channel: SQLServerCentral » SQL Server 2014 » Development - SQL Server 2014 » Latest topics
Viewing all articles
Browse latest Browse all 3145

Is there an easier way to do this than to use a CTE?

$
0
0
Here's the code, followed by the explanation of what I'm wanting to do:[code="sql"]--alter view vwStudentsAPHQualificationSummary asWITH StudentAPH_CTE (DistrictNum, DistrictName, APHQualified, QualificationCount)AS(select st.DistrictNum, ld.DistrictName, APHQualified, 1from vwStudentsFiltered stleft outer join lkupDistricts ld on st.DistrictNum = ld.DistrictNumUNION ALLselect '000' as DistrictNum, '(students unassigned to a district)' as DistrictName, 'Y' as APHQualified, 0 as QualificationCountUNION ALLselect '000' as DistrictNum, '(students unassigned to a district)' as DistrictName, 'N' as APHQualified, 0 as QualificationCountUNION ALLselect '000' as DistrictNum, '(students unassigned to a district)' as DistrictName, 'D' as APHQualified, 0 as QualificationCountUNION ALLselect '000' as DistrictNum, '(students unassigned to a district)' as DistrictName, 'P' as APHQualified, 0 as QualificationCountUNION ALLselect '000' as DistrictNum, '(students unassigned to a district)' as DistrictName, 'PS' as APHQualified, 0 as QualificationCountUNION ALLselect '000' as DistrictNum, '(students unassigned to a district)' as DistrictName, 'S' as APHQualified, 0 as QualificationCount)select DistrictNum, DistrictName, APHQualified, sum(QualificationCount) as QualificationCountfrom StudentAPH_CTEgroup by DistrictNum, DistrictName, APHQualifiedGO[/code]So there are six APH codes: Y, N, D, P, PS, and S. This view feeds an Access crosstab query and report. The reason for the Unions is that, depending on the time of the year, not all of these values may be in use, so I'm forcing them through effectively appending zero count dummy records to the result set. And this works just fine. (I blank the zeroes in the report using format codes)But I'm a little uneasy. I worked on this trying to join the lkupAPHCodes table using various methods with no joy, unfortunately I deleted my attempts so I can't show the approach that I was taking. I'm a firm believer in the SQL 'many ways to do things' paradigm and I'm kinda frustrated that I couldn't make it work in a single statement without using a CTE. I'm not averse to a CTE, I'm just looking for a JOIN version that does the same thing.Any suggestions?

Viewing all articles
Browse latest Browse all 3145

Trending Articles