tags:

views:

139

answers:

1

Does anyone know how I can reproduce this SQL Query as a SubSonic Query?

SELECT PollID, AddedDate, AddedBy, QuestionText, IsCurrent, IsArchived, ArchivedDate,
   (SELECT SUM(Votes) FROM sqsc_PollOptions WHERE PollID = P.PollID) AS Votes
   FROM sqsc_Polls P
   WHERE IsArchived = @IsArchived1 OR IsArchived = @IsArchived2
   ORDER BY AddedDate DESC

I have tried using a View and a aggregate query but it returns no rows when there are no records in the sqsc_PollOptions table which will be the case when creating a new Poll record.

This is how I was querying the view:

return new Select(Aggregate.GroupBy(VwSdPollOption.Columns.PollID, "PollID"), Aggregate.GroupBy(VwSdPollOption.Columns.QuestionText, "QuestionText"), Aggregate.GroupBy(VwSdPollOption.Columns.IsCurrent, "IsCurrent"), Aggregate.Sum(VwSdPollOption.Columns.Votes, "Votes")).From(Views.VwSdPollOption).Where(VwSdPollOption.Columns.CentreName).IsEqualTo(centreName).ExecuteDataSet();

Any help would be greatly appreciated!

+2  A: 

Change your view to this:

   SELECT P.PollID, P.AddedDate, P.AddedBy, P.QuestionText, 
          P.IsCurrent, P.IsArchived, P.ArchivedDate,
          v.Votes
   FROM  sqsc_Polls P left outer join 
         ( SELECT SUM(Votes) as Votes, PollID 
           FROM sqsc_PollOptions group by PollID ) V 
         on P.PollID = V.PollID        
   ORDER BY P.AddedDate DESC

You need to do an outer join to the vote table so that your base poll table fields are still present. Note that Votes will be nullable int. You can fix that by just placing a case statement in the view to return 0 instead of null, or just code around it in your code.

Also, note that I didn't test this and the SQL is from memory, so there might be a typo there. You should be able to figure that out from here.

Jim W
Hi thanks for this I have tried creating the view but I am receiving an error invalid column name 'PollID'?
McDotNet
updated SQL code for you, should resolve the field name now
Jim W
Thanks Jim I am now getting this error multi-part identifier "P.PollID" could not be bound. I cannot see any obvious typos or incorrect field names?
McDotNet
updated sql again. the PollID field is in both tables, so it needed a table identifier in the select statement. I added the table identifier to all of the fields.
Jim W
Thank for all your help Jim!
McDotNet