|
AskSQLTeam
Ask SQLTeam Question
0 Posts |
Posted - 2001-10-03 : 13:39:39
|
Quinn writes "SQL Server 8.00.194, Win2K Pro Service Pack 1.I am working on a query to produce a result set for printing mailing labels in Crystal Reports.The query I have so far returns the results I need for the labels (condensed):AddressId LastName FirstName Address--------- -------- --------- --------------------1 Smith Mary 123 This Street1 Jones Harold 123 This Street2 Powers Reginald 456 That Street2 Powers Nancy 456 That Street3 Johnson Greg 789 The Other Street etc.Now, only one label should go out for each AddressId, which Crystal Reports does nicely by grouping names on addressId. However, a requirement is that the labels must be sorted by last name of one (it doesn't matter which) of the parents. The sample above should come out:Greg Johnson789 The Other StreetReginald PowersNancy Powers456 That StreetMary SmithHarold Jones123 This StreetI can't do a straight forward sort on last name because then that throws the grouping off. What would be nice is an aggregate concatenation on strings like "concat(LastName, ' ', FirstName) as Parents", so the results would be:Parents Address---------------------------- -------------------Smith Mary Jones Harold 123 This StreetPowers Reginald Powers Nancy 456 That StreetJohnson Greg 789 The Other Street I could just sort asc on Parents. Any ideas?Here is the entire query. I think you can ignore the subqueries, unless someone sees a better way. An Account can have zero or more AccountAddresses, which joins Addresses to Parents.SELECT AccountAddress.id, Parent.lastName, Parent.firstName, Address.address1, Address.address2, Address.address3, Address.city, Address.state, Address.zip1, Address.zip2, School.name, School.code, isDropped, sessIdFROM Account, AccountAddress, Address, Parent, ( SELECT child.acctId as acctId, school.name as name, school.code as code FROM School, Child where Child.schId = School.id) As School, ( SELECT child.acctId as acctId, CASE WHEN MAX(dropDate) < current_timestamp AND MIN(ISNULL(dropDate,0)) != cast('1900-01-01' as DATETIME) THEN 1 ELSE 0 END as isDropped FROM Child GROUP BY acctId) AS DroppedWHERE Account.id = AccountAddress.acctIdAND AccountAddress.addrId = Address.IdAND AccountAddress.id = Parent.acAdrIdAND Account.id = School.acctIdAND Account.id = Dropped.acctIdAND Account.sessId = 2GROUP BY AccountAddress.id, Parent.lastName, Parent.firstName, Address.address1, Address.address2, Address.address3, Address.city, Address.state, Address.zip1, Address.zip2, School.name, School.code, isDropped, sessId" |
|