How to write a Linq query equivalent to this SQL - linq-to-sql

I'm trying to figure out how to write a linq query that will return equivalent results to the sql query below. The problem I'm having has to do with the two select count queries included in the select list of the main query. I need to get counts of two different types of records from the PaymentHistory table for the last year. Can the equivalent of this be written using linq? Preferrably using lambda syntax.
select ieinum, serviceaddrkey,
(select count(*) from PaymentHistory where serviceaddrid = serviceaddrkey
and PostDate >= DateAdd(year, -1 , GetDate())
and SetID = 100) as ReturnedFees,
(select count(*) from PaymentHistory where serviceaddrid = serviceaddrkey
and PostDate >= DateAdd(year, -1 , GetDate())
and SetID = 101) as CorrectedReturnedFees
from Serviceaddr
Any help will be great.

Perhaps something like this:
from s in Serviceaddr
let ph = PaymentHistory.Where(p => s.serviceaddrkey == p.serviceaddrkey &&
p.PostDate >= DateTime.Now.AddYears(-1))
select new
{
s.ieinum,
s.serviceaddrkey,
ReturnedFees = ph.Count(p => p.SetID == 100),
CorrectedReturnedFees = ph.Count(p => p.SetID == 101)
}

Related

Select current date item by using ms sql server

I am stucking in sql statement .
Please my query below
select
master_brand.BRAND_NAME as AcCompanyID,
lewre_product.SKU_CODE as AcStockID,
lewre_product.SKU_CODE as BarCode,
lewre_product.SKU_CODE as StockBarCode,
lewre_product.SKU_CODE as StockDescription1,
NULL as StockDescription2,
lewre_project.PROJECT_NAME as AcStockBrandID,
lewre_artice.ARTICLE_NUMBER as AcStockGroupID,
icenter_acStockCategory.CATEGORY_CODE as AcStockCategoryID,
icenter_acStockColor.AcStockColorID as AcStockColorID,
lewre_product.SIZE as AcStockSizeID,
'NA' as ISBN,
master_product_type.UOM as AcStockUOMID,
lewre_article_price.FINAL_COST as StockCost,
lewre_article_price.PRICE as StockPrice1,
0 as StockPrice2,
0 as StockPrice3,
0 as StockPrice4,
0 as StockPrice5,
lewre_artice.CREATE_DATE
from [LEWRE.ARTICLE]as lewre_artice,
[iCENTER.ACSTOCKCATEGORY] as icenter_acStockCategory,
[iCENTER.ACSTOCKCOLOR] as icenter_acStockColor,
[LEWRE.PRODUCT] as lewre_product,
[MASTER.BRAND] as master_brand,
[LEWRE.PROJECT] as lewre_project,
[MASTER.PRODUCT_TYPE] as master_product_type,
[LEWRE.ARTICLE_PRICE] as lewre_article_price
where
(icenter_acStockCategory.CATEGORY_ID = lewre_artice.PRODUCT_CATEGORY_ID
AND icenter_acStockCategory.PRODUCT_TYPE_ID = lewre_artice.PRODUCT_TYPE_ID)
AND lewre_product.ARTICLE_ID = lewre_artice.ARTICLE_ID
and lewre_product.COLOR_ID = icenter_acStockColor.COLOR_ID
and master_brand.BRAND_ID = lewre_artice.BRAND_ID
and lewre_artice.PROJECT_ID = lewre_project.PROJECT_ID
and master_product_type.PRODUCT_TYPE_ID = lewre_artice.PRODUCT_TYPE_ID
and lewre_artice.ARTICLE_ID = lewre_article_price.ARTICLE_ID
and lewre_artice.CREATE_DATE
order by lewre_artice.CREATE_DATE
Here is the result that i get
I want to select all row which create_date is current date.for example (2012-04-30)' . How can i get the result? Please help me
Add this to your where clause.
lewre_artice.CREATE_DATE >= cast(getdate() as date) and
lewre_artice.CREATE_DATE < cast(dateadd(day, 1, getdate()) as date)
getdate() returns the current timestamp and cast(getdate() as date) removes the time part. dateadd(day, 1, ....) adds one day. The comparison returns the rows where CREATE_DATE is within the interval.

LINQ TO SQL: HAVING COUNT(table_id) < 2

I'm building a website for an school and i need a list of users that don't have 2 parents asigned. This would be the SQL query:
SQL
SELECT * FROM users
WHERE user_rol = 4
AND user_id IN
(SELECT parent_user_id FROM user_parents
GROUP BY parent_user_id
HAVING COUNT(parent_user_id) < 2);
I'm trying to use LINQ for the same query but I don't know how to use HAVING with LINQ. This has been my closer try for the moment.
SUB-QUERY FOR IN
List<long> usersWithTwoParentsIds = (from currentStudents in contexto.user_parents
select currentStudents.parent_user_id).ToList<long>();
--HELP! having count(currentStudents.parent_user_id) < 2
QUERY
List<vw_user> userList = (from currentStudents in contexto.vw_user
where !usersWithTwoParentsIds.Contains(currentStudents.user_id)
&& currentStudents.group_id == groupID select currentStudents).ToList<vw_user>()
Can anybody give a clue? Thanks :)
Something like this:
var usersWithTwoParentsIds = (
from userParent in contexto.user_parents
group userParent by userParent.parent_user_id into userParentGroups
where userParentGroups.Count() < 2
select userParentGroups.Key)
.ToList();
Assuming the key relations are proper in your data context:
var dat = Context.Users.Where( u => u.Parents.Count() < 2 );

grouping by non-database field

How can I group a query result by a field that is not saved in the database.
For example I want to group the result by duration which is came from subtraction of start time and end time.
here is how i find out the duration
date1= $row_TicketRS['CloseDate'];
$date2 = $row_TicketRS['OpenDate'];
$diff = abs(strtotime($date2) - strtotime($date1));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
if ( $days > 0)
{
$time1 = $row_TicketRS['OpenTime'];
$time2= $row_TicketRS['CloseTime'];
$t1=($time1);
$t2=($time2);
$end=('14:30');
$start=('07:30');
$n = $end- $t1;
$n2 = $t2- $start;
$Hours2 = floor(($n+$n2)+(($days-1)*7));
echo $Hours2.' Hours';
but know i do not know how to add it to the query
here is my query
$strQuery = "SELECT count(`ticket`.TicketID) as TotOutput, department.`DeptName` FROM `ticket`, `user`, department where ticket.OwnerID = user.EmpNo and user.`DepartmentID` = department.`DepartmentID` and OpenDate between'".$DateFrom."' And '".$DateTo."'"
It'd be better to have details, but a derived table/inline view would allow you to group by a computed value:
SELECT x.duration,
COUNT(*)
FROM (SELECT t.col,
t.end_time - t.start_time AS duration
FROM YOUR_TABLE t) x
GROUP BY x.duration
How about adding that computed value to the query with an alias like this:
SELECT some_fields, end - start AS duration FROM table ORDER BY duration
dont put alias for hidden column , use directly
exmaple:
SELECT id, FLOOR(value/100)
FROM tbl_name
GROUP BY id, FLOOR(value/100);
Reference
MySQL permits expressions in GROUP BY
clauses, so the alias is unnecessary:

Creating LINQ to SQL for counting a parameter

I'm trying to translate a sql query into LINQ to SQL. I keep getting an error "sequence operators not supported for type 'system.string'" If I take out the distinct count part, it works. Is it not because I'm using the GROUP BY?
SELECT COUNT(EpaValue) AS [Leak Count], Location, EpaValue AS [Leak Desc.]
FROM ChartMes.dbo.RecourceActualEPA_Report
WHERE (EpaName = N'LEAK1') AND (Timestamp) > '20100429030000'
GROUP BY EpaValue, Location
ORDER BY Location, [Leak Count] DESC
Dim temp = (From p In db2.RecourceActualEPA_Reports _
Where (p.Timestamp >= str1stShiftStart) And (p.Timestamp < str2ndShiftCutoff) _
And (p.EpaName = "Leak1") _
Select p.EpaName.Distinct.Count(), p.Location, p.EpaValue)
p.EpaName seems to be a string, not a collection so you can't apply Count() there.
Here is the query you're trying to build (according to your SQL query) using LINQ (I'm not familiar with VB, so the query is written in C#):
var temp =
db2.RecourceActualEPA_Reports
.Where(p =>
p.Timestamp >= str1stShiftStart &&
p.Timestamp < str2ndShiftCutoff &&
p.EpaName == "Leak1"
).GroupBy(p => new { Key1 = p.EpaValue, Key2 = p.Location })
.Select(g => new
{
Count = g.Count(),
Value = g.Key.Key1,
Location = g.Key.Key2
}).OrderBy(i => new { i.Location, i.Count });
And please, in the future format and highlight your code using this, not (or not only) using VS/Management Studio.
Here is how it is formatted in SQL and in Visual Studio
SQL
SELECT COUNT(EpaValue) AS [Leak Count], Location, EpaValue AS [Leak Desc.]
FROM ChartMes.dbo.RecourceActualEPA_Report
WHERE (EpaName = N'LEAK1') AND (Timestamp) > '20100429030000'
GROUP BY EpaValue, Location
ORDER BY Location, [Leak Count] DESC
VB
Dim temp = (From p In db2.RecourceActualEPA_Reports _
Where (p.Timestamp >= str1stShiftStart) And (p.Timestamp < str2ndShiftCutoff) _
And (p.EpaName = "Leak1") _
Select p.EpaName.Distinct.Count(), p.Location, p.EpaValue)

Beginner LINQ syntax question

I have a basic SQL Table ( pKey INT, TransDate smallDateTime, Amount Float)
I simply want to emulate this SQL in LINQ
SELECT SUM(Amount) AS result
FROM dbo.Basic
WHERE TransDate >= #startDate
AND TransDate <= #EndDate
I have created the LINQ dbml for this and I can get basic query results for a date range
However I can't find the right syntax to get the SUM over a dateRange, I've tried several variations on the following but either they dont compile, or the result they give cannot be converted to a double
BasicDataContext dContext = new BasicDataContext();
var lnq = from c in dContext.Basic
where c.TransDate >= startdate &&
c.TransDate <= enddate
select new { total = c.Sum(Amount) };
double result = (double)lnq.total;
This should work:
double result = (from c in dContext.Basic
where c.TransDate >= startdate &&
c.TransDate <= enddate
select c.Amount).Sum();