Click here to Skip to main content
15,905,229 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I want to select all columns with group by clause using linq. In mysql, query is like:

SQL
select *,count(ContactNumber) as TotalCount from (select SMSBodyText,SentDateTime, ContactNumber from `ars_tmc`.`sms`
where ModuleID=24 and SMSTypeID=1  order by SentDateTime desc) as a group by ContactNumber order by SentDateTime desc;


and output is:
CSS
SMSBodyText           SentDateTime       ContactNumber   TotalSMS
Hi Dipali test msg-3  11-10-2014 11:42    919425001480     2
hi                    10-10-2014 07:29    918378803988     1


my linq is:

XML
var SubQuery = (from sms in UtilService.DtSMSInbox.AsEnumerable()
                            orderby sms.Field<DateTime>("SentDateTime") descending
                            select sms);
            var MainQuery = (from sms1 in SubQuery
                             let SentDateTime = sms1.Field<DateTime>("SentDateTime")
                             let SMSBodyText = sms1.Field<string>("SMSBodyText")
                             group sms1 by (sms1.Field<string>("ContactNumber")) into grouping

                             select new
                             {
                                 ContactNumber = grouping.Key,
                                 count = grouping.Count(),
                                 items=grouping,
                             });


but i m not able to select all columns. Please help me with the solution.

Thanx in Advance
Posted

1 solution

First of all the SQL statement looks a bit odd. The idea in GROUP BY is that you define all the columns that are used to define a unique combination of data in a group. Then again you can select these columns in the SELECT clause and use aggregates on other columns. Because of this an asterisk (*) doesn't make sense in the query.

So to include all desired columns, use column names instead of asterisk in both SQL statement and in the LINQ query.

See SQL GROUP BY Statement[^] and How to: Handle Composite Keys in Queries[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900