Sql Query to EF Linq Expression - sql

Can anybody help with this sql Query to tranform it to EF Linq Expression?
SELECT Aitimata.id, AST.dateCr, AST.StatusId, Aitimata.UniqueCode, Aitimata.CategoryId, Aitimata.Thema
FROM Aitimata INNER JOIN
(select a.* from AitimataStatus a join
(select AitimaId, max(dateCr) AS dateCr
from AitimataStatus
group by AitimaId) b
on a.AitimaId = b.AitimaId and a.dateCr = b.dateCr)as AST ON Aitimata.id = AST.AitimaId
The important is this subquery
select a.* from AitimataStatus a join
(select AitimaId, max(dateCr) AS dateCr
from AitimataStatus
group by AitimaId) b
on a.AitimaId = b.AitimaId and a.dateCr = b.dateCr
you need extra info?
Thanks

It'll be something like this:
from a in AitimataStatus
let b = from as in AitimataStatus group by and other stuff and then select
join b on a.** equals b.**

Here is my solution
Dim sub1 = From aitst In context.AitimataStatus
Join aitst2 In (From aitst2 In context.AitimataStatus
Group aitst2 By cid = aitst2.AitimaId Into g = Group
Select New With {.AitimaId = cid, .dateCr = g.Max(Function(ddd) (ddd.dateCr))}
)
On aitst2.AitimaId Equals aitst.AitimaId And aitst2.dateCr Equals aitst.dateCr
Select aitst
it produce
SELECT
[Extent1].[id] AS [id],
[Extent1].[dateCr] AS [dateCr],
[Extent1].[UserId] AS [UserId],
[Extent1].[AitimaId] AS [AitimaId],
[Extent1].[StatusId] AS [StatusId]
FROM [dbo].[AitimataStatus] AS [Extent1]
INNER JOIN (SELECT
[Extent2].[AitimaId] AS [K1],
MAX([Extent2].[dateCr]) AS [A1]
FROM [dbo].[AitimataStatus] AS [Extent2]
GROUP BY [Extent2].[AitimaId] ) AS [GroupBy1] ON (([Extent1].[AitimaId] = [GroupBy1].[K1]) OR (([Extent1].[AitimaId] IS NULL) AND ([GroupBy1].[K1] IS NULL))) AND (([Extent1].[dateCr] = [GroupBy1].[A1]) OR (([Extent1].[dateCr] IS NULL) AND ([GroupBy1].[A1] IS NULL)))
.

Related

trying to modifying a multi join query with issues

I have a simplified query shown below, that does mulitple joins. I'm trying to add a field to be selected but I am unable to find a good way of joining it without changing the number of records that come up...
SELECT tblApp.AppID
,'Type' = tblRef.Label
,'Status' = tblRef2.Label
FROM (
(
(
tblApp LEFT JOIN tblAppExt ON tblApp.AppID = tblAppExt.AppID
) LEFT JOIN tblRef ON tblApp.AppTypeID = tblReferenceData.ID
) LEFT JOIN tblRef tblRef2 ON tblApp.AppStatusID = tblRef2.ID
)
As is - I'm getting 149 results, if I try to Join it in any way, I get like 10 time fold the number of records. All I'm hoping to do is be able to SELECt another field. I'm hoping to join tblAppExt2 that has AppID just like the other tables in the FROM part of the query, so my goal would basically be to do this:
SELECT tblApp.AppID
,'Type' = tblRef.Label
,'Status' = tblRef2.Label
,'NewField' = tblAppExt2.NewField
First thing to try is DISTINCT:
SELECT DISTINCT
tblApp.AppID
, [Type] = tblRef.Label
, [Status] = tblRef2.Label
, [NewField] = tblAppExt2.NewField
FROM tblApp
LEFT JOIN tblAppExt
ON tblApp.AppID = tblAppExt.AppID
LEFT JOIN tblRef
ON tblApp.AppTypeID = tblReferenceData.ID
LEFT JOIN tblRef tblRef2
ON tblApp.AppStatusID = tblRef2.ID
LEFT JOIN tblAppExt2.NewField
ON something = somethingElse ;
If that doesn't work, it means there are multiple different values for [NewField] and you'll need to tell it how to select the correct one. For example, to take the most recent [NewField] you can use a CTE with the ROW_NUMBER function:
; WITH AllRecords
AS (
SELECT DISTINCT
tblApp.AppID
, [Type] = tblRef.Label
, [Status] = tblRef2.Label
, [NewField] = tblAppExt2.NewField
, MyRank = ROW_NUMBER() OVER(PARTITION BY tblApp.ID ORDER BY tblAppExt2.DateEntered DESC)
FROM tblApp
LEFT JOIN tblAppExt
ON tblApp.AppID = tblAppExt.AppID
LEFT JOIN tblRef
ON tblApp.AppTypeID = tblReferenceData.ID
LEFT JOIN tblRef tblRef2
ON tblApp.AppStatusID = tblRef2.ID
LEFT JOIN tblAppExt2.NewField
ON something = somethingElse
)
SELECT *
FROM AllRecords
WHERE AllRecords.MyRank = 1 ;
You can use outer apply or correlated subquery :
SELECT tblApp.AppID, tblRef.Label as [Type], tblRef2.Label as [Status],
tappext.NewField
FROM tblApp tapp LEFT JOIN
tblAppExt tex
ON tapp.AppID = tex.AppID LEFT JOIN
tblRef tref
ON tapp.AppTypeID = tref.ID LEFT JOIN
tblRef tblRef2
ON tapp.AppStatusID = tblRef2.ID OUTER APPLY
( SELECT TOP (1) tappext.*
FROM tblAppExt2 tappext
WHERE tapp.AppID = AppID
ORDER BY ??
) tappext;

Convert Exist condition to Join with T-SQL

I am trying to convert the following T-SQL Select query to exclude "Exists" Clause and Include "Join" Clause. but i am ending up not getting the right result. can some one from this expert team help me with some tips.
select *
FROM HRData
INNER JOIN (
SELECT eeceeid, MIN(eecdateoftermination) eTermDate
FROM dbo.empcomp
INNER JOIN
(
SELECT xeeid FROM HRData_EEList
INNER JOIN dbo.empcomp t ON xeeid = eeceeid AND xcoid = eeccoid
WHERE eecemplstatus = 'T' AND eectermreason <> 'TRO' AND eeccoid <> 'WAON6'
AND EXISTS ( SELECT 1 FROM dbo.empded
INNER JOIN dbo.dedcode on deddedcode = eeddedcode AND deddedtype = 'MED' AND (eedbenstopdate IS NULL OR eedbenstopdate > '12/31/2005')
WHERE eedeeid = xeeid AND eedcoid = xcoid )
GROUP BY xeeid
HAVING COUNT(*) > 1) Term ON xeeid = eeceeid
group by eeceeid
) Terms ON eeid = eeceeid AND Termdate = eTermDate
The algorithm to convert EXISTS to JOIN is very simple.
Instead of
FROM A
WHERE EXISTS (SELECT *
FROM B
WHERE A.Foo = B.Foo)
Use
FROM A
INNER JOIN (SELECT DISTINCT Foo
FROM B) AS B
ON A.Foo = B.Foo
But the first one probably will be optimised better
Interesting request.
select *
FROM HRData
INNER JOIN (
SELECT eeceeid, MIN(eecdateoftermination) eTermDate
FROM dbo.empcomp
INNER JOIN
(
SELECT xeeid FROM HRData_EEList
INNER JOIN dbo.empcomp t ON xeeid = eeceeid AND xcoid = eeccoid
INNER JOIN
( SELECT DISTINCT xeeid, xcoid FROM dbo.empded
INNER JOIN dbo.dedcode on deddedcode = eeddedcode AND deddedtype = 'MED' AND (eedbenstopdate IS NULL OR eedbenstopdate > '12/31/2005')
-- WHERE eedeeid = xeeid AND eedcoid = xcoid
) AS A ON xeeid = A.xeeid AND eedcoid = A.eedcoid
WHERE eecemplstatus = 'T' AND eectermreason <> 'TRO' AND eeccoid <> 'WAON6'
GROUP BY xeeid
HAVING COUNT(*) > 1) Term ON xeeid = eeceeid
group by eeceeid
) Terms ON eeid = eeceeid AND Termdate = eTermDate
Another method of converting an exists to a join is to use a ROW_NUMBER() in the subselect to assist in removing duplicates.
EXISTS:
FROM A
WHERE EXISTS (SELECT *
FROM B
WHERE B.Condition = 'true' AND A.Foo = B.Foo)
JOIN:
FROM A
JOIN (SELECT B.Foo, ROW_NUMBER() OVER (PARTITION BY B.Foo ORDER BY B.Foo) RN
FROM B
WHERE B.Condition = 'true') DT
ON A.Foo = DT.Foo AND DT.RN = 1
The ORDER BY is totally arbitrary since you don't care which record it selects, but it's required. You may be able to use (SELECT NULL) instead.

How to Reduce Execution Time

It's just my startup in SQL, I have 4.5 GB database from that I am trying to select records from specific dates and its 25 seconds execute. Is there a way to make it faster?
My query:
select a.*,b.ModelName
from Validation a
left Join ModelMaster b
on SUBSTRING(a.STB,11,2) = b.ProductCode and
Convert(int,substring(a.STB,9,2)) = b.BrandCode
Where STB in (Select STB From Scan_Data_For_Century) and
a.date between '2015-01-14' and '2015-01-14'
You can try query like this:
SELECT a.*,
b.ModelName
FROM Scan_Data_For_Century sd
INNER JOIN Validation a
ON a.STB = sd.STB AND a.date between '2015-01-14' and '2015-01-14'
LEFT JOIN ModelMaster b
ON SUBSTRING(a.STB,11,2) = b.ProductCode AND Convert(int,substring(a.STB,9,2)) = b.BrandCode
I know, that must be a comment. Please, try query. If it wont help I will remove my answer.
Try this:
;with cte as (
select
*,
ProductCode = SUBSTRING( STB, 11, 2 ),
BrandCode = Convert( int, substring( STB, 9, 2 ) )
from Validation
)
select
a.*,
c.ModelName
from
cte a
inner join Scan_Data_For_Century b on ( b.STB = a.STB )
left Join ModelMaster c on ( c.ProductCode = b.ProductCode ) and ( c.BrandCode = b.BrandCode )
Where
( a.date = '2015-01-14' )
Also indexes on:
Validation.STB
Validation.Date
Scan_Data_For_Century.STB
ModelMaster.ProductCode
ModelMaster.BrandCode
might be helpfull

SQL Server Conditional Join instead of WHERE .. IN .. clauses

SELECT A.Name, H.Name as BookedBy
FROM dbo.vwAllLoads A WITH (NOEXPAND)
LEFT JOIN dbo.SystemInfo H
ON (A.BookedByUserID = H.GlobalNetUserID)
WHERE ((A.CustomerID IN (SELECT UCR.CustomerID
FROM dbo.UserCustomerRelations UCR
WHERE UCR.UserID IN
(SELECT UserID FROM #PodUsers)
OR H.GlobalUserID IN
(SELECT UserID FROM #PodUsers)))
Now I filter data using above where clause. How can I accomplish the same using joins or in a better way?
Please help
Assuming your query is something like:
select a.*
from a
where A.CustomerID IN (SELECT UCR.CustomerID
FROM dbo.UserCustomerRelations UCR
WHERE UCR.UserID IN (SELECT UserID FROM #PodUsers) OR
UCR.GlobalNetUserID IN (SELECT UserID FROM #PodUsers)
-----------------------------^ was `H`, I'm assuming is `UCR`
)
Then the following should be an equivalent query using joins:
select distinct a.*
from a join
dbo.UserCustomerRelations ucr
on A.CustomerID = ucr.CustomerID join
#PodUsers pu
on ucr.UserId = pu.UserId or ucr.UserId = ucr.GlobalNetUserID = pu.UserId;
The distinct would be unnecessary if you know that the joins do not produce multiple rows
I guess something like this:
INNER JOIN [dbo].[UserCustomerRelations] UCR
ON A.[CustomerID] = UCR.[CustomerID]
INNER JOIN #PodUsers PU
ON UCR.[CustomerID] = PD.[UserID]
OR H.[GlobalNetUserID] = PD.[UserID]

MSSQL Inner Join on Concatenated Column

I'm not a DBA so please don't yell at me. Trying to do an inner join and Group By using a concatenated column. The ON statement is producing a syntax error. I do not have access to the original tables and am trying to normalize this into another table, I know its ugly. Not overly worried about performance, just need to work. Cant use functions either.
SELECT DISTINCT A.[carrier_code],[carrier_name], [carrier_grouping], A.[collector_name], [dataset_loaded], [docnum], [envoy_payer_id], [loc], [market], [master_payor_grouping], [plan_class], [plan_name], A.[resp_ins],A.[resp_ind], A.[resp_payor_grouping], A.[Resp_Plan_Type], A.[rspphone], A.[state], A.[sys],A.[resp_ins]+A.[resp_payor_grouping]+A.[carrier_code]+A.[state]+A.[Collector_Name] as ExtId
FROM [Table1] A
INNER JOIN
(SELECT [resp_ins]+[resp_payor_grouping]+[carrier_code]+[state]+[Collector_Name] as Extid
FROM [Table1]
WHERE [resp_ind] = 'Insurance'
GROUP BY [resp_ins]+[resp_payor_grouping]+[carrier_code]+[state]+[Collector_Name]) B
ON A.[resp_ins]+A.[resp_payor_grouping]+A.[carrier_code]+A.[state]+A.[Collector_Name] = B.[resp_ins]+B.[resp_payor_grouping]+B.[carrier_code]+B.[state]+B.[Collector_Name];
My ON and Group By statements are eventually the primary key in new table.
Your alias B hasn't columns as you mentioned. It has just on column Extid.
SELECT DISTINCT A.[carrier_code],[carrier_name], [carrier_grouping], A.[collector_name], [dataset_loaded], [docnum], [envoy_payer_id], [loc], [market], [master_payor_grouping], [plan_class], [plan_name], A.[resp_ins],A.[resp_ind], A.[resp_payor_grouping], A.[Resp_Plan_Type], A.[rspphone], A.[state], A.[sys],A.[resp_ins]+A.[resp_payor_grouping]+A.[carrier_code]+A.[state]+A.[Collector_Name] as ExtId
FROM [Table1] A
INNER JOIN
(SELECT [resp_ins]+[resp_payor_grouping]+[carrier_code]+[state]+[Collector_Name] as Extid
FROM [Table1]
WHERE [resp_ind] = 'Insurance'
GROUP BY [resp_ins]+[resp_payor_grouping]+[carrier_code]+[state]+[Collector_Name]) B
ON A.[resp_ins]+A.[resp_payor_grouping]+A.[carrier_code]+A.[state]+A.[Collector_Name] = B.Extid;
Try this, I didn't put all the column in result, you can manage yourself.
select A.*
from
(
select [carrier_code],[carrier_name], [sys],[resp_ins]+[resp_payor_grouping]+[carrier_code]+[state]+[Collector_Name] as ExtId
FROM [Table1]
) A
inner join
(
select distinct Extid
from
(
SELECT [resp_ins]+[resp_payor_grouping]+[carrier_code]+[state]+[Collector_Name] as ExtId
FROM [Table1]
WHERE [resp_ind] = 'Insurance'
) ins
) B on (A.ExtId = B.ExtId)
You don't need to concatenate the values - you can GROUP BY and JOIN on multiple columns.
SELECT DISTINCT
...
FROM
[Table1] A
INNER JOIN
(
SELECT
[resp_ins],
[resp_payor_grouping],
[carrier_code],
[state],
[Collector_Name]
FROM
[Table1]
WHERE
[resp_ind] = 'Insurance'
GROUP BY
[resp_ins],
[resp_payor_grouping],
[carrier_code],
[state],
[Collector_Name]
) B
ON
(
A.[resp_ins] = B.[resp_ins]
Or
(A.[resp_ins] Is Null And B.[resp_ins] Is Null)
)
And
(
A.[resp_payor_grouping] = B.[resp_payor_grouping]
Or
(A.[resp_payor_grouping] Is Null And B.[resp_payor_grouping] Is Null)
)
And
(
A.[carrier_code] = B.[carrier_code]
Or
(A.[carrier_code] Is Null And B.[carrier_code] Is Null)
)
And
(
A.[state] = B.[state]
Or
(A.[state] Is Null And B.[state] Is Null)
)
And
(
A.[Collector_Name] = B.[Collector_Name]
Or
(A.[Collector_Name] Is Null And B.[Collector_Name] Is Null)
)
;