Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Linq: count(distinct) conversion

$
0
0

hi folks

I'm having trouble converting the following (functional) SQL statement into Linq

SELECT     TOP (100) PERCENT UsrComp, CurrentDate, COUNT(DISTINCT [User]) AS UniqueUsers

FROM         dbo.UserLogs
GROUP BY UsrComp, CurrentDate
ORDER BY UsrComp, CurrentDate

USE [Rhonda]

i've tried these 2 attempts with Linq:

having trouble with this (just via 101 LinqPad):

from c in UserLogs
group c by new {c.UsrComp, c.CurrentDate} into grp
orderby grp.Key.UsrComp, grp.Key.Currentdate
select new { Comp = grp.Key.UsrComp, Date = grp.Key.CurrentDate, User_Count=grp.Select(x = > x.User).Distinct().Count() }

*and this*:

from c in UserLogs
group c by new {c.UsrComp, c.CurrentDate, c.User} into grp
orderby grp.Key.UsrComp, grp.Key.CurrentDate, grp.User

select new { Comp = grp.Key.UsrComp, Date = grp.Key.CurrentDate, User_Count=grp.Select(x = > grp.Key.User).Distinct().Count() }

definitions:

GO
/****** Object:  Table [dbo].[UserLogs]    Script Date: 4/18/2014 10:58:23 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[UserLogs](
[UserLogID] [int] IDENTITY(1,1) NOT NULL,
[UsrComp] [nvarchar](20) NOT NULL,
[User] [nvarchar](20) NOT NULL,
[CurrentDate] [date] NOT NULL,
[TimeRecorded] [datetime] NOT NULL,
 CONSTRAINT [PK_UserLogs] PRIMARY KEY CLUSTERED 
(
[UserLogID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

data:

1ABCJohn2014-01-012014-01-01 10:15:00.000
2ABCJohn2014-01-012014-01-01 16:15:00.000
3ABCMary2014-01-012014-01-01 12:15:00.000
4ABCJohn2014-01-022014-01-01 10:15:00.000
5DEFRhonda2014-01-022014-01-01 10:15:00.000
6DEFRob2014-01-012014-01-01 12:15:00.000
7DEFRob2014-01-012014-01-01 16:15:00.000
8DEFRob2014-01-012014-01-01 10:15:00.000


Rob K


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>