CROSS APPLY too slow for running total - TSQL - performance

Please see my code below as it is running too slowly with the CROSS APPLY.
How can I remove the CROSS APPLY and add something else that will run faster?
Please note I am using SQL Server 2008 R2.
;WITH MyCTE AS
(
SELECT
R.NetWinCURRENCYValue AS NetWin
,dD.[Date] AS TheDay
FROM
dimPlayer AS P
JOIN
dbo.factRevenue AS R ON P.playerKey = R.playerKey
JOIN
dbo.vw_Date AS dD ON Dd.dateKey = R.dateKey
WHERE
P.CustomerID = 12345)
SELECT
A.TheDay AS [Date]
,ISNULL(A.NetWin, 0) AS NetWin
,rt.runningTotal AS CumulativeNetWin
FROM MyCTE AS A
CROSS APPLY (SELECT SUM(NetWin) AS runningTotal
FROM MyCTE WHERE TheDay <= A.TheDay) AS rt
ORDER BY A.TheDay

CREATE TABLE #temp (NetWin money, TheDay datetime)
insert into #temp
SELECT
R.NetWinCURRENCYValue AS NetWin
,dD.[Date] AS TheDay
FROM
dimPlayer AS P
JOIN
dbo.factRevenue AS R ON P.playerKey = R.playerKey
JOIN
dbo.vw_Date AS dD ON Dd.dateKey = R.dateKey
WHERE
P.CustomerID = 12345;
SELECT
A.TheDay AS [Date]
,ISNULL(A.NetWin, 0) AS NetWin
,SUM(B.NetWin) AS CumulativeNetWin
FROM #temp AS A
JOIN #temp AS B
ON A.TheDay >= B.TheDay
GROUP BY A.TheDay, ISNULL(A.NetWin, 0);

Here https://stackoverflow.com/a/13744550/613130 it's suggested to use recursive CTE.
;WITH MyCTE AS
(
SELECT
R.NetWinCURRENCYValue AS NetWin
,dD.[Date] AS TheDay
,ROW_NUMBER() OVER (ORDER BY dD.[Date]) AS RN
FROM dimPlayer AS P
JOIN dbo.factRevenue AS R ON P.playerKey = R.playerKey
JOIN dbo.vw_Date AS dD ON Dd.dateKey = R.dateKey
WHERE P.CustomerID = 12345
)
, MyCTERec AS
(
SELECT C.TheDay AS [Date]
,ISNULL(C.NetWin, 0) AS NetWin
,ISNULL(C.NetWin, 0) AS CumulativeNetWin
,C.RN
FROM MyCTE AS C
WHERE C.RN = 1
UNION ALL
SELECT C.TheDay AS [Date]
,ISNULL(C.NetWin, 0) AS NetWin
,P.CumulativeNetWin + ISNULL(C.NetWin, 0) AS CumulativeNetWin
,C.RN
FROM MyCTERec P
INNER JOIN MyCTE AS C ON C.RN = P.RN + 1
)
SELECT *
FROM MyCTERec
ORDER BY RN
OPTION (MAXRECURSION 0)
Note that this query will work if you have 1 record == 1 day! If you have multiple records in a day, the results will be different from the other query.

As I said here, if you want really fast calculation, put it into temporary table with sequential primary key and then calculate rolling total:
create table #Temp (
ID bigint identity(1, 1) primary key,
[Date] date,
NetWin decimal(29, 10)
)
insert into #Temp ([Date], NetWin)
select
dD.[Date],
sum(R.NetWinCURRENCYValue) as NetWin,
from dbo.dimPlayer as P
inner join dbo.factRevenue as R on P.playerKey = R.playerKey
inner join dbo.vw_Date as dD on Dd.dateKey = R.dateKey
where P.CustomerID = 12345
group by dD.[Date]
order by dD.[Date]
;with cte as (
select T.ID, T.[Date], T.NetWin, T.NetWin as CumulativeNetWin
from #Temp as T
where T.ID = 1
union all
select T.ID, T.[Date], T.NetWin, T.NetWin + C.CumulativeNetWin as CumulativeNetWin
from cte as C
inner join #Temp as T on T.ID = C.ID + 1
)
select C.[Date], C.NetWin, C.CumulativeNetWin
from cte as C
order by C.[Date]
I assume that you could have duplicates dates in the input, but don't want duplicates in the output, so I grouped data before puting it into the table.

Related

I want to take thus code for stratified sampling in SQL server and convert it to Oracle 12c

WITH row_count AS (
select s1.rec_count, (0.313733*s1.rec_count)/(0.0001*(s1.rec_count-1)+0.313733) as calc_count from (
SELECT count(*) AS rec_count
FROM staging.denodo_sample_clinical_event_s1 a
INNER JOIN DENODO.DIM_CLINICAL_EVENT_CLASS b ON a.CLINICAL_EVENT_CLASS_ID = b.CLINICAL_EVENT_CLASS_ID
WHERE b.CLINICAL_EVENT_SAMPLE_GROUP = 's7_Radiology'
)s1
)
SELECT s.clinical_event_id,s.clinical_event_class_id,s.clinical_event_code_id
FROM staging.denodo_sample_clinical_event_s1 s
INNER JOIN denodo.dim_clinical_event_class d ON d.clinical_event_class_id = s.clinical_event_class_id
cross join row_count c
WHERE d.clinical_event_sample_group = 's7_Radiology'
AND c.calc_count/c.rec_count >= CAST(CHECKSUM(NEWID(), s.clinical_event_id) & 0x7fffffff AS float)
/ CAST (0x7fffffff AS int);
CHECKSUM returns as integer that is a hash of the argument values.
NEWID generates a random GUID.
So, you appear to be hashing a random GUID and an event id which will give you a (semi?) random number and then performing a binary AND to restrict it to an upper-bound and then dividing by that upper-bound to get a decimal value in the range from 0 to 1.
If you just want a random value in the range from 0 to less than 1 then use DBMS_RANDOM.VALUE().
Which would make your query:
WITH row_count AS (
select rec_count,
(0.313733*rec_count)/(0.0001*(rec_count-1)+0.313733) as calc_count
from (
SELECT count(*) AS rec_count
FROM staging.denodo_sample_clinical_event_s1 a
INNER JOIN DENODO.DIM_CLINICAL_EVENT_CLASS b
ON a.CLINICAL_EVENT_CLASS_ID = b.CLINICAL_EVENT_CLASS_ID
WHERE b.CLINICAL_EVENT_SAMPLE_GROUP = 's7_Radiology'
)
)
SELECT s.clinical_event_id,
s.clinical_event_class_id,
s.clinical_event_code_id
FROM staging.denodo_sample_clinical_event_s1 s
INNER JOIN denodo.dim_clinical_event_class d
ON d.clinical_event_class_id = s.clinical_event_class_id
cross join row_count c
WHERE d.clinical_event_sample_group = 's7_Radiology'
AND c.calc_count/c.rec_count >= DBMS_RANDOM.VALUE();
If you find that the random values are not being randomly generated for each cross join then you may need to use a technique like in this answer and include some seemingly irrelevant filters. (However, we don't have your tables or data so I am unsure if it would be necessary).
Or, if you want to use ORA_HASH:
WITH row_count AS (
select rec_count,
(0.313733*rec_count)/(0.0001*(rec_count-1)+0.313733) as calc_count
from (
SELECT count(*) AS rec_count
FROM staging.denodo_sample_clinical_event_s1 a
INNER JOIN DENODO.DIM_CLINICAL_EVENT_CLASS b
ON a.CLINICAL_EVENT_CLASS_ID = b.CLINICAL_EVENT_CLASS_ID
WHERE b.CLINICAL_EVENT_SAMPLE_GROUP = 's7_Radiology'
)
)
SELECT s.clinical_event_id,
s.clinical_event_class_id,
s.clinical_event_code_id
FROM staging.denodo_sample_clinical_event_s1 s
INNER JOIN denodo.dim_clinical_event_class d
ON d.clinical_event_class_id = s.clinical_event_class_id
cross join row_count c
WHERE d.clinical_event_sample_group = 's7_Radiology'
AND c.calc_count/c.rec_count
>= ORA_HASH(
SYS_GUID() || s.clinical_event_id,
134217727,
FLOOR(DBMS_RANDOM.VALUE(0, 4294967296)) -- random seed
) / 134217727;
INSERT INTO DENODO.SAMPLE_CASE_CLINICAL_EVENT (
CLINICAL_EVENT_ID
,CLINICAL_EVENT_CLASS_ID
,CLINICAL_EVENT_CODE_ID
,EVENT_ID
)
WITH row_count AS (
SELECT count
,(0.313733 * count) / (0.0001 * (count - 1) + 0.313733) AS calc_count
FROM (
SELECT count(*) AS count
FROM DENODO.MT_BASE_CLINICAL_EVENT_98_ETL_SQL a
INNER JOIN DENODO.DIM_CLINICAL_EVENT_CLASS b ON a.CLINICAL_EVENT_CLASS_ID = b.CLINICAL_EVENT_CLASS_ID
WHERE b.CLINICAL_EVENT_SAMPLE_GROUP = 's7_Radiology'
)
)
SELECT /*+ parallel (5) */ a.CLINICAL_EVENT_ID
,a.CLINICAL_EVENT_CLASS_ID
,a.CLINICAL_EVENT_CODE_ID
,a.EVENT_ID
FROM DENODO.MT_BASE_CLINICAL_EVENT_98_ETL_SQL a
INNER JOIN DENODO.DIM_CLINICAL_EVENT_CLASS b ON
a.CLINICAL_EVENT_CLASS_ID = b.CLINICAL_EVENT_CLASS_ID
CROSS JOIN row_count c
WHERE c.calc_count / c.count >=
bitand(ORA_HASH(SYS_GUID() || CLINICAL_EVENT_ID),
to_number('7fffffff', 'xxxxxxxxx')) / to_number('7fffffff', 'xxxxxxxxx')
AND CLINICAL_EVENT_SAMPLE_GROUP = 's7_Radiology';

How to avoid Internal_Function by TO_CHAR IN Oracle

I'm using Oracle 12C and I have the following code:
SELECT *
FROM
(
SELECT
*
FROM
t.tablea
WHERE
name = 'FIS'
) A
LEFT JOIN (
SELECT
*
FROM
t.tableb
WHERE
enabled = 1
) B ON b.id = a.id
AND TO_CHAR(b.createdate, 'dd-mm-yy hh24:mi') = TO_CHAR(a.createdate, 'dd-mm-yy hh24:mi')
Both a and b createdate are timestamp datatype.
Optimizer return an internal_function at TO_CHAR(b.createdate, 'dd-mm-yy hh24:mi') = TO_CHAR(a.createdate, 'dd-mm-yy hh24:mi') in Execution Plan
If I compare like this: 'AND b.createdate = a.createdate', It will lost 1000 rows that look like this '11-JUN-18 04.48.34.269928000 PM'. And If I change 269928000 to 269000000 It will work
Now, I don't want to using to_char to avoid internal_function(must create Function-based-Index)
Anyone can help me?
If I compare like this: AND b.createdate = a.createdate, It will lost 1000 rows that look like this 11-JUN-18 04.48.34.269928000 PM. And If I change 269928000 to 269000000 It will work
Your values appear to have a fractional seconds component and would have the TIMESTAMP data type. If so, you can use TRUNC( timestamp_value, 'MI' ) to truncate to the nearest minute.
SELECT *
FROM t.tablea a
LEFT OUTER JOIN t.tableb b
ON ( a.createdate >= TRUNC( b.createdate, 'MI' )
AND a.createdate < TRUNC( b.createdate, 'MI' ) + INTERVAL '1' MINUTE
AND a.id = b.id
AND b.enabled = 1
)
WHERE a.name = 'FIS'
This will remove the need to apply a function to one of the two tables (a.createdate in this case but you could swap them).
I don't even see the need for the subqueries:
SELECT a.*, b.*
FROM t.tablea a
LEFT JOIN t.tableb b
ON a.id = b.id AND
TRUNC(b.createdate, 'MI') = TRUNC(a.createdate, 'MI') AND
b.enabled = 1
WHERE
a.name = 'FIS'

How can I join these two select queries into one query?

this is my first time posting, so I am sure I will get a number of things wrong. Do not hesitate to correct me and I will do everything I can to clarify.
In Oracle SQL Developer, I am trying to take two separate SELECT statements and combine them to get one row of results. Unfortunately, because this is sensitive data, I am unable to give any results from the statements individually, but instead, just the SQL statements themselves. I suspect I should be able to join these two on the field "emplid" but just cannot get there. Any help is greatly appreciated! Here is the code below, please mind the syntax :)
1st Select statement is giving me a list of people that were paid in 2017:
SELECT DISTINCT C.COMPANY,
C.EMPLID,
C.SSN
FROM PS_PAY_CHECK C
WHERE TO_CHAR(C.CHECK_DT,'YYYY') = '2017'
AND C.COMPANY IN ('001','054','076')
ORDER BY C.COMPANY, C.EMPLID
And 2nd Select statement would be a list of the deductions taken for the employees that were identified in the first statement:
SELECT G.EMPLID, G.DEDCD,
CASE
WHEN DC.DED_CLASS IN ('A','B','T')
THEN G.DED_ADDL_AMT
ELSE 0
END AS "EEAmt",
CASE
WHEN DC.DED_CLASS NOT IN ('A','B','T')
THEN G.DED_ADDL_AMT
ELSE 0
END AS "ERAmt",
DC.DED_CLASS,
G.DED_ADDL_AMT,
G.GOAL_AMT
FROM PS_GENL_DEDUCTION G,
PS_DED_CLASS_VW DC
WHERE G.EFFDT =
(SELECT MAX(G_ED.EFFDT)
FROM PS_GENL_DEDUCTION G_ED
WHERE G.EMPLID = G_ED.EMPLID
AND G.COMPANY = G_ED.COMPANY
AND G.DEDCD = G_ED.DEDCD
AND G_ED.EFFDT <= SYSDATE
)
AND ( G.DEDUCTION_END_DT IS NULL
OR G.DEDUCTION_END_DT > SYSDATE)
AND ( G.GOAL_AMT = 0.00
OR G.GOAL_AMT <> G.GOAL_BAL)
AND G.DED_ADDL_AMT > 0
AND DC.PLAN_TYPE = '00'
AND DC.DEDCD = G.DEDCD
AND DC.EFFDT =
(SELECT MAX(V1.EFFDT)
FROM PS_DED_CLASS_VW V1
WHERE V1.PLAN_TYPE = DC.PLAN_TYPE
AND V1.DEDCD = DC.DEDCD
)
AND G.EMPLID = 'XXXXXX'
Ideally, what I'd like to do is put in a value in place of 'XXXXXX' and get one row of data with the two combined statements.
Thanks everyone!
To do this, we stick each SELECT statement into a subquery and give that subquery an alias to refer to in the main queries select statement:
SELECT t1.*, t2.*
FROM
(
SELECT DISTINCT C.COMPANY,
C.EMPLID,
C.SSN
FROM PS_PAY_CHECK C
WHERE TO_CHAR(C.CHECK_DT,'YYYY') = '2017'
AND C.COMPANY IN ('001','054','076')
ORDER BY C.COMPANY, C.EMPLID
) t1
INNER JOIN
(
SELECT G.EMPLID, G.DEDCD,
CASE
WHEN DC.DED_CLASS IN ('A','B','T')
THEN G.DED_ADDL_AMT
ELSE 0
END AS "EEAmt",
CASE
WHEN DC.DED_CLASS NOT IN ('A','B','T')
THEN G.DED_ADDL_AMT
ELSE 0
END AS "ERAmt",
DC.DED_CLASS,
G.DED_ADDL_AMT,
G.GOAL_AMT
FROM PS_GENL_DEDUCTION G,
PS_DED_CLASS_VW DC
WHERE G.EFFDT =
(SELECT MAX(G_ED.EFFDT)
FROM PS_GENL_DEDUCTION G_ED
WHERE G.EMPLID = G_ED.EMPLID
AND G.COMPANY = G_ED.COMPANY
AND G.DEDCD = G_ED.DEDCD
AND G_ED.EFFDT <= SYSDATE
)
AND ( G.DEDUCTION_END_DT IS NULL
OR G.DEDUCTION_END_DT > SYSDATE)
AND ( G.GOAL_AMT = 0.00
OR G.GOAL_AMT <> G.GOAL_BAL)
AND G.DED_ADDL_AMT > 0
AND DC.PLAN_TYPE = '00'
AND DC.DEDCD = G.DEDCD
AND DC.EFFDT =
(SELECT MAX(V1.EFFDT)
FROM PS_DED_CLASS_VW V1
WHERE V1.PLAN_TYPE = DC.PLAN_TYPE
AND V1.DEDCD = DC.DEDCD
)
AND G.EMPLID = 'XXXXXX'
) t2 ON
t1.empid = t2.empid
We just treat each derived table/subquery as it's own table and join them on empid. You can tweak the SELECT statement at the top as needed.
This is similar to creating a view for both sql statements and then referencing the views in a third sql statement.
An alternative way of doing this is to use CTE (Common Table Expressions) to house the separate sql. There's no performance advantage here, but you might find it easier to read.
WITH t1 as
(
SELECT DISTINCT C.COMPANY,
C.EMPLID,
C.SSN
FROM PS_PAY_CHECK C
WHERE TO_CHAR(C.CHECK_DT,'YYYY') = '2017'
AND C.COMPANY IN ('001','054','076')
ORDER BY C.COMPANY, C.EMPLID
),
t2 AS
(
SELECT G.EMPLID, G.DEDCD,
CASE
WHEN DC.DED_CLASS IN ('A','B','T')
THEN G.DED_ADDL_AMT
ELSE 0
END AS "EEAmt",
CASE
WHEN DC.DED_CLASS NOT IN ('A','B','T')
THEN G.DED_ADDL_AMT
ELSE 0
END AS "ERAmt",
DC.DED_CLASS,
G.DED_ADDL_AMT,
G.GOAL_AMT
FROM PS_GENL_DEDUCTION G,
PS_DED_CLASS_VW DC
WHERE G.EFFDT =
(SELECT MAX(G_ED.EFFDT)
FROM PS_GENL_DEDUCTION G_ED
WHERE G.EMPLID = G_ED.EMPLID
AND G.COMPANY = G_ED.COMPANY
AND G.DEDCD = G_ED.DEDCD
AND G_ED.EFFDT <= SYSDATE
)
AND ( G.DEDUCTION_END_DT IS NULL
OR G.DEDUCTION_END_DT > SYSDATE)
AND ( G.GOAL_AMT = 0.00
OR G.GOAL_AMT <> G.GOAL_BAL)
AND G.DED_ADDL_AMT > 0
AND DC.PLAN_TYPE = '00'
AND DC.DEDCD = G.DEDCD
AND DC.EFFDT =
(SELECT MAX(V1.EFFDT)
FROM PS_DED_CLASS_VW V1
WHERE V1.PLAN_TYPE = DC.PLAN_TYPE
AND V1.DEDCD = DC.DEDCD
)
AND G.EMPLID = 'XXXXXX'
)
SELECT t1.*, t2.*
FROM t1 INNER JOIN t2 ON
t1.empid = t2.empid
Basically you do something like
select blah, blah.. (your second query )
AND G.EMPLID IN ( SELECT DISTINCT C.COMPANY,
C.EMPLID,
C.SSN
FROM PS_PAY_CHECK C
WHERE TO_CHAR(C.CHECK_DT,'YYYY') = '2017'
AND C.COMPANY IN ('001','054','076')
)
So basically I have used your first query in you second query. I removed the DISTINCT, as its not needed.
I hope that makes sense.

How can we use partition in Oracle query

I have query in which i used partition of avoid the duplicate value for particular column , but still it is giving duplicate row below i am mention my query in which i used partition
SELECT iol.M_product_id as faultyProduct , iol.SERIALNO,iol.M_product_id as newproduct, ma.Description,
mp.M_Product_category_id ,mi.issotrx, co.C_BPartner_ID,
ROW_NUMBER() OVER(PARTITION BY ma.Description ORDER BY iol.M_product_id DESC) rn
FROM M_inoutline iol
inner join M_inout mi ON (iol.m_inout_id = mi.m_inout_id)
inner join C_Order co ON (co.c_order_id = mi.c_order_id )
inner Join M_AttributeSetInstance ma ON (ma.m_attributesetinstance_id =iol.m_attributesetinstance_id)
inner join M_Product mp ON (mp.m_product_id = iol.m_product_id)
where mp.m_product_category_id= 1000447 AND mi.issotrx = 'Y';
Please help me out
For me it looks you want to do:
select * from (/*YOUR QUERY*/) where rn = 1;

Linq to entities query adding inner join instead of left join

I'd like to know why INNER JOINs are generated instead of LEFT and why the whole view is selected before join instead of just adding LEFT JOIN view.
I'm trying to post a table of information which is spread out over several tables. Basically I want to search by the date and return all the information for events happening today, yesterday, this month - whatever the user selects. The query is quite long. I added DefaultIfEmpty to all the tables except the main one in an attempt to get LEFT JOINs but it just made a mess.
using (TransitEntities t = new TransitEntities())
{
var charters = from c in t.tblCharters
join v in t.tblChartVehicles.DefaultIfEmpty()
on c.Veh
equals v.ChartVehID
join n in t.tblNACharters.DefaultIfEmpty()
on c.Dpt.Substring(c.Dpt.Length - 1)
equals SqlFunctions.StringConvert((double)n.NAID)
join r in t.tblChartReqs.DefaultIfEmpty()
on c.ChartReqID
equals r.ChartReqID
join f in t.tblCharterCustomers.DefaultIfEmpty()
on c.Dpt
equals (f.DptID == "NONAFF" ? SqlFunctions.StringConvert((double)f.CustID) : f.DptID)
join d in t.tblChartReqDocs.DefaultIfEmpty()
on c.Attach
equals SqlFunctions.StringConvert((double)d.DocID)
join s in t.tblChartSupAttaches.DefaultIfEmpty()
on c.SupAttach
equals SqlFunctions.StringConvert((double)s.DocID)
join p in (from e in t.v_EmpData select new {e.UIN, e.First, e.Last}).DefaultIfEmpty()
on c.TakenUIN
equals p.UIN
where c.BeginTime > EntityFunctions.AddYears(DateTime.Now,-1)
select new
{
ChartID = c.ChartID,
Status = c.Status,
...
Website = r.Website,
};
//select today's events
gvCharters.DataSource = charters.Where(row => (row.BeginTime.Value >= midnight && row.BeginTime.Value < midnight1));
This results in very convoluted SQL:
SELECT
[Extent1].[ChartID] AS [ChartID],
[Extent1].[Status] AS [Status],
...
[Join5].[Website] AS [Website],
FROM [dbo].[tblCharters] AS [Extent1]
INNER JOIN (SELECT [Extent2].[ChartVehID] AS [ChartVehID], [Extent2].[Descr] AS [Descr]
FROM ( SELECT 1 AS X ) AS [SingleRowTable1]
LEFT OUTER JOIN [dbo].[tblChartVehicles] AS [Extent2] ON 1 = 1 ) AS [Join1] ON ([Extent1].[Veh] = [Join1].[ChartVehID]) OR (([Extent1].[Veh] IS NULL) AND ([Join1].[ChartVehID] IS NULL))
INNER JOIN (SELECT [Extent3].[NAID] AS [NAID], [Extent3].[Descr] AS [Descr]
FROM ( SELECT 1 AS X ) AS [SingleRowTable2]
LEFT OUTER JOIN [dbo].[tblNACharter] AS [Extent3] ON 1 = 1 ) AS [Join3] ON ((SUBSTRING([Extent1].[Dpt], ((LEN([Extent1].[Dpt])) - 1) + 1, (LEN([Extent1].[Dpt])) - ((LEN([Extent1].[Dpt])) - 1))) = (STR( CAST( [Join3].[NAID] AS float)))) OR ((SUBSTRING([Extent1].[Dpt], ((LEN([Extent1].[Dpt])) - 1) + 1, (LEN([Extent1].[Dpt])) - ((LEN([Extent1].[Dpt])) - 1)) IS NULL) AND (STR( CAST( [Join3].[NAID] AS float)) IS NULL))
INNER JOIN (SELECT [Extent4].[ChartReqID] AS [ChartReqID], [Extent4].[Event] AS [Event], [Extent4].[ContactName] AS [ContactName], [Extent4].[ContactPhone] AS [ContactPhone], [Extent4].[Website] AS [Website]
FROM ( SELECT 1 AS X ) AS [SingleRowTable3]
LEFT OUTER JOIN [dbo].[tblChartReq] AS [Extent4] ON 1 = 1 ) AS [Join5] ON ([Extent1].[ChartReqID] = [Join5].[ChartReqID]) OR (([Extent1].[ChartReqID] IS NULL) AND ([Join5].[ChartReqID] IS NULL))
INNER JOIN (SELECT [Extent5].[CustID] AS [CustID], [Extent5].[Dpt] AS [Dpt], [Extent5].[DptID] AS [DptID]
FROM ( SELECT 1 AS X ) AS [SingleRowTable4]
LEFT OUTER JOIN [dbo].[tblCharterCustomers] AS [Extent5] ON 1 = 1 ) AS [Join7] ON ([Extent1].[Dpt] = (CASE WHEN (N'NONAFF' = [Join7].[DptID]) THEN STR( CAST( [Join7].[CustID] AS float)) ELSE [Join7].[DptID] END)) OR (([Extent1].[Dpt] IS NULL) AND (CASE WHEN (N'NONAFF' = [Join7].[DptID]) THEN STR( CAST( [Join7].[CustID] AS float)) ELSE [Join7].[DptID] END IS NULL))
INNER JOIN (SELECT [Extent6].[DocID] AS [DocID], [Extent6].[FileName] AS [FileName]
FROM ( SELECT 1 AS X ) AS [SingleRowTable5]
LEFT OUTER JOIN [dbo].[tblChartReqDocs] AS [Extent6] ON 1 = 1 ) AS [Join9] ON ([Extent1].[Attach] = (STR( CAST( [Join9].[DocID] AS float)))) OR (([Extent1].[Attach] IS NULL) AND (STR( CAST( [Join9].[DocID] AS float)) IS NULL))
INNER JOIN (SELECT [Extent7].[DocID] AS [DocID], [Extent7].[FileName] AS [FileName]
FROM ( SELECT 1 AS X ) AS [SingleRowTable6]
LEFT OUTER JOIN [dbo].[tblChartSupAttach] AS [Extent7] ON 1 = 1 ) AS [Join11] ON ([Extent1].[SupAttach] = (STR( CAST( [Join11].[DocID] AS float)))) OR (([Extent1].[SupAttach] IS NULL) AND (STR( CAST( [Join11].[DocID] AS float)) IS NULL))
INNER JOIN (SELECT [Extent8].[First] AS [First], [Extent8].[Last] AS [Last], [Extent8].[UIN] AS [UIN]
FROM ( SELECT 1 AS X ) AS [SingleRowTable7]
LEFT OUTER JOIN (SELECT
[v_EmpData].[First] AS [First],
[v_EmpData].[Last] AS [Last],
[v_EmpData].[Legal] AS [Legal],
[v_EmpData].[Name] AS [Name],
[v_EmpData].[Email] AS [Email],
[v_EmpData].[UIN] AS [UIN],
[v_EmpData].[UserNM] AS [UserNM],
[v_EmpData].[Worker] AS [Worker],
[v_EmpData].[SUPERVISORNUM] AS [SUPERVISORNUM],
[v_EmpData].[Supervisor] AS [Supervisor],
[v_EmpData].[EmpArea] AS [EmpArea],
[v_EmpData].[Title] AS [Title],
[v_EmpData].[FullName] AS [FullName],
[v_EmpData].[HireDate] AS [HireDate],
[v_EmpData].[WORKERTYPENM] AS [WORKERTYPENM],
[v_EmpData].[Birth] AS [Birth],
[v_EmpData].[HOMESTREET] AS [HOMESTREET],
[v_EmpData].[HOMECITY] AS [HOMECITY],
[v_EmpData].[HOMEZIP] AS [HOMEZIP],
[v_EmpData].[HOMESTATE] AS [HOMESTATE],
[v_EmpData].[PicID] AS [PicID],
[v_EmpData].[WorkPhone] AS [WorkPhone],
[v_EmpData].[HomePhone] AS [HomePhone],
[v_EmpData].[WorkCellPhone] AS [WorkCellPhone]
FROM [dbo].[v_EmpData] AS [v_EmpData]) AS [Extent8] ON 1 = 1 ) AS [Join13] ON ([Extent1].[TakenUIN] = [Join13].[UIN]) OR (([Extent1].[TakenUIN] IS NULL) AND ([Join13].[UIN] IS NULL))
WHERE ([Extent1].[BeginTime] > (DATEADD (year, -1, SysDateTime())))
AND ('C' <> [Extent1].[Status])
AND ([Extent1].[BeginTime] >= '11/28/2012 12:00:00 AM')
AND ([Extent1].[BeginTime] < '11/29/2012 12:00:00 AM')
This is what my original SQL query looked like and what I was hoping it would be closer to:
SELECT
ChartID,
c.Status,
...
r.Website As Website,
FROM tblChartersNew c
LEFT JOIN (SELECT [Dpt],[DptID] FROM [DRVRDiscipline].[dbo].[tblCharterCustomers] Where Valid=1 and DptID <> 'NONAFF' UNION SELECT Dpt, CONVERT(nvarchar,CustID) AS DptID FROM [DRVRDiscipline].[dbo].[tblCharterCustomers] Where Valid=1 and DptID = 'NONAFF') f
ON RTRIM(c.Dpt) = f.DptID LEFT JOIN [tskronos].WfcSuite.dbo.VP_ALLPERSONV42 p ON p.PersonNUM = c.TakenUIN
LEFT JOIN tblChartVehicles v ON v.ChartVehID = c.Veh
LEFT JOIN tblNACharter n ON CAST(n.NAID AS varchar) = RIGHT(c.Dpt, LEN(c.Dpt)-1)
LEFT JOIN tblChartReq r
ON r.ChartReqID = c.ChartReqID
WHERE CONVERT(datetime,CONVERT(char(10),c.BeginTime,101)) = (SELECT TOP 1 CONVERT(datetime,CONVERT(char(10),BeginTime,101)) from tblChartersNew WHERE CONVERT(datetime,CONVERT(char(10),BeginTime,101)) >= CONVERT(datetime,CONVERT(char(10),GETDATE(),101)) ORDER BY BeginTime)
AND NOT c.ChartReqID IS NULL
ORDER BY BeginTime, ISNULL(f.Dpt,c.Dpt)
I also add a Select New on the view to avoid selecting all of the columns when I only need three but it didn't seem to make a difference. Instead of adding LEFT JOIN v_EmpData it adds LEFT OUTER JOIN and then selects all of the columns in the view. It seems to be ignoring the Select New.
I'd really like to transition to using Linq to Entities for the majority of my queries because intellisense makes it so much easier to make sure it's right and to have variations of queries without having to have separate functions for each but maybe I need to stick with plain old SQL. I know just enough to make a big mess. Any suggestions?
For complex queries like what you need.
I would suggest looking into FunctionImport.
MSDN Function Import
This would save you the headache of creating a LINQ that would be 1:1 to your expected generated SQL.

Resources