I'm struggling to figure out the best way to write this query to use less queries if possible.. I'm wondering if a pivot table might be the correct way?
My 3 separate queries:
SELECT
ISNULL(SUM(ps.UnitsSold), 0) AS UnitsSold,
ISNULL(pg.[Description], 'Other') AS [Description]
FROM dbo.ProductSales ps
LEFT OUTER JOIN dbo.Product p ON ps.ProductID = p.ProductID
LEFT OUTER JOIN dbo.ProductGroupings pg ON p.[Asin] = pg.[Asin]
WHERE (ps.OrderDate BETWEEN GETDATE() - 10 AND GETDATE() - 3) AND ps.DistributionCentreID IN (3)
GROUP BY pg.[Description], ps.DistributionCentreID
SELECT
ISNULL(SUM(ps.UnitsSold), 0) AS UnitsSold,
ISNULL(pg.[Description], 'Other') AS [Description]
FROM dbo.ProductSales ps
LEFT OUTER JOIN dbo.Product p ON ps.ProductID = p.ProductID
LEFT OUTER JOIN dbo.ProductGroupings pg ON p.[Asin] = pg.[Asin]
WHERE (ps.OrderDate BETWEEN GETDATE() - 17 AND GETDATE() - 10) AND ps.DistributionCentreID IN (3)
GROUP BY pg.[Description], ps.DistributionCentreID
SELECT
ISNULL(SUM(ps.UnitsSold), 0) AS UnitsSold,
ISNULL(pg.[Description], 'Other') AS [Description]
FROM dbo.ProductSales ps
LEFT OUTER JOIN dbo.Product p ON ps.ProductID = p.ProductID
LEFT OUTER JOIN dbo.ProductGroupings pg ON p.[Asin] = pg.[Asin]
WHERE (ps.OrderDate BETWEEN GETDATE() - 374 AND GETDATE() - 367) AND ps.DistributionCentreID IN (3)
GROUP BY pg.[Description], ps.DistributionCentreID
This produces results similar to this (first query):
UnitsSold Description
4154 desc1
764 desc2
etc..
Things to think about, a description (product group) might not exist in one of the queries so I need to account for that.
Ideally I'd like it to look a little something like this:
Description UnitsSoldThisWeek UnitsSoldLastWeek UnitsSoldLastYear
Desc1 54 45 37
etc..
Any questions, issues or bitching due to bad query is acceptable, I'm happy to improve my understanding of SQL.
Thanks,
Michael
Do this with one query and conditional aggregation:
SELECT coalesce(pg.[Description], 'Other') AS [Description],
sum(case when ps.OrderDate BETWEEN GETDATE() - 10 AND GETDATE() - 3 then UnitsSold
end) as ThisWeek
sum(case when ps.OrderDate BETWEEN GETDATE() - 17 AND GETDATE() - 10 then UnitsSold
else 0
end) as LastWeek,
sum(case when ps.OrderDate BETWEEN GETDATE() - 374 AND GETDATE() - 367 then UnitsSold
else 0
end) as LastYear
FROM dbo.ProductSales ps LEFT OUTER JOIN
dbo.Product p
ON ps.ProductID = p.ProductID LEFT OUTER JOIN
dbo.ProductGroupings pg
ON p.[Asin] = pg.[Asin]
WHERE ps.DistributionCentreID IN (3)
GROUP BY pg.[Description], ps.DistributionCentreID
i've changed your query a little to show a different technique which will combine your 3 queries. I may not have the brackets quite right round the SUMS but that gives you an idea. There are also better ways to do the sort of "date between" stuff you are trying, but that wasn't the question! See if that helps
SELECT
ISNULL(SUM(ps.UnitsSold), 0) AS UnitsSold,
ISNULL(pg.[Description], 'Other') AS [Description]
SUM(CASE WHEN (ps.OrderDate BETWEEN GETDATE() - 10 AND GETDATE() - 3) AND ps.DistributionCentreID = 3 THEN 1 ELSE 0 END) AS UnitsSoldThisWeek
SUM(CASE WHEN (ps.OrderDate BETWEEN GETDATE() - 17 AND GETDATE() - 10) AND ps.DistributionCentreID = 3 THEN 1 ELSE 0 END) AS UnitsSoldThisWeek
SUM(CASE WHEN (ps.OrderDate BETWEEN GETDATE() - 374 AND GETDATE() - 367) AND ps.DistributionCentreID = 3 THEN 1 ELSE 0 END) AS UnitsSoldThisWeek
FROM dbo.ProductSales ps
LEFT OUTER JOIN dbo.Product p ON ps.ProductID = p.ProductID
LEFT OUTER JOIN dbo.ProductGroupings pg ON p.[Asin] = pg.[Asin]
GROUP BY pg.[Description], ps.DistributionCentreID
;WITH CTE AS (
Select [UnitsSoldThisWeek],[UnitsSoldLastWeek],[UnitsSoldLastYear] FROM (
SELECT
ISNULL(SUM(ps.UnitsSold), 0) AS UnitsSold,
ISNULL(pg.[Description], 'Other') AS [Description]
FROM dbo.ProductSales ps
LEFT OUTER JOIN dbo.Product p ON ps.ProductID = p.ProductID
LEFT OUTER JOIN dbo.ProductGroupings pg ON p.[Asin] = pg.[Asin]
WHERE (ps.OrderDate BETWEEN GETDATE() - 10 AND GETDATE() - 3) AND ps.DistributionCentreID IN (3)
GROUP BY pg.[Description], ps.DistributionCentreID
UNION ALL
SELECT
ISNULL(SUM(ps.UnitsSold), 0) AS UnitsSold,
ISNULL(pg.[Description], 'Other') AS [Description]
FROM dbo.ProductSales ps
LEFT OUTER JOIN dbo.Product p ON ps.ProductID = p.ProductID
LEFT OUTER JOIN dbo.ProductGroupings pg ON p.[Asin] = pg.[Asin]
WHERE (ps.OrderDate BETWEEN GETDATE() - 17 AND GETDATE() - 10) AND ps.DistributionCentreID IN (3)
GROUP BY pg.[Description], ps.DistributionCentreID
UNION ALL
SELECT
ISNULL(SUM(ps.UnitsSold), 0) AS UnitsSold,
ISNULL(pg.[Description], 'Other') AS [Description]
FROM dbo.ProductSales ps
LEFT OUTER JOIN dbo.Product p ON ps.ProductID = p.ProductID
LEFT OUTER JOIN dbo.ProductGroupings pg ON p.[Asin] = pg.[Asin]
WHERE (ps.OrderDate BETWEEN GETDATE() - 374 AND GETDATE() - 367) AND ps.DistributionCentreID IN (3)
GROUP BY pg.[Description], ps.DistributionCentreID
)
PIVOT(MAX(UnitsSold)FOR Description IN([UnitsSoldThisWeek],[UnitsSoldLastWeek],[UnitsSoldLastYear])) )
)
Select [UnitsSoldThisWeek],[UnitsSoldLastWeek],[UnitsSoldLastYear] from CTE
i am not quite sure because lack of data but we can proceed like this also
Related
Currently I have a table that I am forming with a UNION in order to calculate two different SUMS. Right now I have duplicate rows because one of the SUM's is null in each to perform the UNION.
This is what my table looks like now:
Table Preview
I would like to simply combine the rows with identical SKU's. Below is what I have so far
DECLARE #dt1 AS DATETIME
SET #dt1 = DATEADD(day, 0, '2021/5/1')
DECLARE #dt2 AS DATETIME
SET #dt2 = DATEADD(day, -30, getDate())
(SELECT
OD.[SKU] AS SKU,
OD.[ProductName] AS Name,
SUM(OD.[Qty]) AS #OrderedAllTime,
null AS #OrderedInLast30Days,
(W.Onhand - W.Committed) as Available FROM ORD_OrderDetail AS OD
LEFT JOIN INV_OptionItemsKeys AS IK ON OD.SkuID = IK.SubItemID
INNER JOIN ORD_order AS O ON OD.ordernumber = O.recordnumber
JOIN INV_WarehouseItems W on OD.SkuID = W.ItemID WHERE O.Invoicedate IS NOT NULL
AND O.void <> 1
AND O.OrderDate > #dt1 GROUP BY OD.[SKU], OD.[ProductName], IK.[key], W.ItemID, W.OnHand, W.Committed)
UNION ALL
(SELECT
OD.[SKU] AS SKU,
OD.[ProductName] AS Name,
null AS #OrderedAllTime,
SUM(OD.[Qty]) AS #OrderedInLast30Days,
(W.Onhand - W.Committed) as Available FROM ORD_OrderDetail AS OD
LEFT JOIN INV_OptionItemsKeys AS IK ON OD.SkuID = IK.SubItemID
INNER JOIN ORD_order AS O ON OD.ordernumber = O.recordnumber
JOIN INV_WarehouseItems W on OD.SkuID = W.ItemID WHERE O.Invoicedate IS NOT NULL
AND O.void <> 1
AND O.OrderDate > #dt2 GROUP BY OD.[SKU], OD.[ProductName], IK.[key], W.ItemID, W.OnHand, W.Committed)
I think your friend is CASE statement.
SELECT
OD.[SKU] AS SKU,
OD.[ProductName] AS Name,
SUM(CASE WHEN O.OrderDate > #dt1 THEN OD.[Qty] ELSE 0 END) AS #OrderedAllTime,
SUM(CASE WHEN O.OrderDate > #dt1 THEN 0 ELSE OD.[Qty]) END) AS #OrderedInLast30Days,
(W.Onhand - W.Committed) as Available
FROM ORD_OrderDetail AS OD
LEFT JOIN INV_OptionItemsKeys AS IK ON OD.SkuID = IK.SubItemID
INNER JOIN ORD_order AS O ON OD.ordernumber = O.recordnumber
JOIN INV_WarehouseItems W on OD.SkuID = W.ItemID
WHERE O.Invoicedate IS NOT NULL
AND O.void <> 1
AND O.OrderDate > #dt2
GROUP BY OD.[SKU], OD.[ProductName], IK.[key], W.ItemID, W.OnHand, W.Committed)
I'm running the following query on our SQL Server DB.
The query takes at least 20 minutes to complete. I don't have permissions on the db to run execution plan
Thoughts or suggestions on what to try would be appreciated
SELECT
UsageDate,
--convert(date,dateadd(day, 22 - 1,dateadd(month,cast(datepart("MM", dateadd("d",-21, getdate()-2)) as int)- 1,dateadd(year,cast(datepart("yyyy", dateadd("d",23,getdate()-2)) as int) - 2000,'2000-01-01'))) ) AS BILLING_CYCLE_START_DT,
(sum(MVNO301TotUsg)-sum(ROAMING_3G_LTE)) MB,
sum(ROAMING_3G_LTE)ROAMING_3G_LTE,
case when convert(date,UsageDate) = convert(date,dateadd(day, 9 - 1,dateadd(month,cast(datepart("MM", dateadd("d",-8, getdate()-2)) as int)- 1,dateadd(year,cast(datepart("yyyy", dateadd("d",10,getdate()-2)) as int) - 2000,'2000-01-01'))) )
then 100000000 else 0 end as BeginBaseAvgMB
FROM
(
select convert(date,EVENT_DT) UsageDate,
sum((USAGE_KB_3G+LTE_USAGE_KB+EHRPD_USAGE_KB)/1024)AS MVNO301TotUsg,
0 ROAMING_3G_LTE
from [spmp].[dbo].SubscriberCombinedUsageallmvnos USG with (NOLOCK)
JOIN aMVNO.dbo.Subscribers S with (NOLOCK) ON USG.subscriberkey =S.subscriberkey
left Join aMVNO.dbo.exMVNOs_Realm_RISE RLM with (NOLOCK) ON S.SubscriberNumber = RLM.SBSCR_NBR
where (RESELLER_ID = 'a9')
and convert(date,EVENT_DT) between dateadd(d,-33,GETDATE()) and dateadd(d,-2,GETDATE())
group by convert(date,EVENT_DT)
UNION ALL
SELECT
convert(date,EVENT_DT) UsageDate,
0 AS MVNO301TotUsg,
sum(DOMESTIC_ROAM_3G + INTERNATIONAL_ROAM_3G +GSM_3G +ROAMING_LTE_KB)/1024 ROAMING_3G_LTE
from [spmp].[dbo].SubscriberCombinedUsageallmvnos USG with (NOLOCK)
JOIN aMVNO.dbo.Subscribers S with (NOLOCK) ON USG.subscriberkey =S.subscriberkey
left Join aMVNO.dbo.exMVNOs_Realm_RISE RLM with (NOLOCK) ON S.SubscriberNumber = RLM.SBSCR_NBR
JOIN [aMVNO].[dbo].[BusinessDate] BD WITH (NOLOCK) ON convert(date,USG.EVENT_DT) =convert(date,BD.DT)
where
(RESELLER_ID = 'a9')
and convert(date,EVENT_DT) between dateadd(d,-33,GETDATE()) and dateadd(d,-2,GETDATE())
GROUP BY
convert(date,EVENT_DT)
)Z
group by UsageDate
ORDER BY USAGEDATE
I have the following query (as part of a larger query). I am trying to get the sum results from 2 different data sets within a subquery but I am having trouble trying to encapsulate the two into 1 value. What I have is this:
(Select SUM('Invoiced MTD') from
((Select SUM(CASE WHEN SOH.LASDLVNUM_0 <> '' AND SOH.LASINVNUM_0 <> '' AND MONTH(SOH.SHIDAT_0) = MONTH(GETDATE()) THEN
(SOP.NETPRI_0 * SOQ.QTY_0 * SOH.CHGRAT_0) ELSE 0 END) as 'Invoiced MTD'
From x3v6.CICPROD.SORDER SOH
LEFT OUTER JOIN x3v6.CICPROD.BPCUSTOMER BPC on SOH.BPCORD_0 = BPC.BPCNUM_0
LEFT OUTER JOIN x3v6.CICPROD.SORDERQ SOQ on SOH.SOHNUM_0 = SOQ.SOHNUM_0
LEFT OUTER JOIN x3v6.CICPROD.SORDERP SOP on SOQ.SOHNUM_0 = SOP.SOHNUM_0 and SOQ.SOPLIN_0 = SOP.SOPLIN_0 and SOQ.SOQSEQ_0 = SOP.SOPSEQ_0
LEFT OUTER JOIN x3v6.CICPROD.ITMMASTER ITM on SOP.ITMREF_0 = ITM.ITMREF_0 ))
UNION ALL
((Select SUM(CASE WHEN SIH.INVTYP_0 = 2 and MONTH(SIH.ACCDAT_0) = MONTH(GETDATE()) THEN SID.AMTNOTLIN_0 * (-1) ELSE 0 END) as 'Invoiced MTD'
From x3v6.CICPROD.SINVOICE SIH
Left Outer Join x3v6.CICPROD.SINVOICED SID on SIH.NUM_0 = SID.NUM_0))
as 'T2',
But I am getting an error where the UNION ALL clauses is, and I can't figure it out. Basically I want to combine Sales credit memos with the sales order dollar totals from a seperate table.
Can anyone assist me with this?
What about this ?
Select SUM([Invoiced MTD]) from
(
Select SUM(CASE WHEN SOH.LASDLVNUM_0 <> '' AND SOH.LASINVNUM_0 <> '' AND MONTH(SOH.SHIDAT_0) = MONTH(GETDATE())
THEN (SOP.NETPRI_0 * SOQ.QTY_0 * SOH.CHGRAT_0) ELSE 0 END) as 'Invoiced MTD'
From x3v6.CICPROD.SORDER SOH
LEFT OUTER JOIN x3v6.CICPROD.BPCUSTOMER BPC on SOH.BPCORD_0 = BPC.BPCNUM_0
LEFT OUTER JOIN x3v6.CICPROD.SORDERQ SOQ on SOH.SOHNUM_0 = SOQ.SOHNUM_0
LEFT OUTER JOIN x3v6.CICPROD.SORDERP SOP on SOQ.SOHNUM_0 = SOP.SOHNUM_0 and SOQ.SOPLIN_0 = SOP.SOPLIN_0 and SOQ.SOQSEQ_0 = SOP.SOPSEQ_0
LEFT OUTER JOIN x3v6.CICPROD.ITMMASTER ITM on SOP.ITMREF_0 = ITM.ITMREF_0
UNION ALL
Select SUM(CASE WHEN SIH.INVTYP_0 = 2 and MONTH(SIH.ACCDAT_0) = MONTH(GETDATE())
THEN SID.AMTNOTLIN_0 * (-1) ELSE 0 END) as 'Invoiced MTD'
From x3v6.CICPROD.SINVOICE SIH
Left Outer Join x3v6.CICPROD.SINVOICED SID on SIH.NUM_0 = SID.NUM_0
)T
Does this work? I'm not sure exactly what is causing your issue, but you definitely don't need so many parenthesis. I would also recommend using something that formats/ beautifies your SQL. It's a great way to 1) keep your code looking consistent and 2) flesh out syntax errors.
SELECT SUM(x.invoiced_mtd)
FROM (SELECT SUM(CASE
WHEN soh.lasdlvnum_0 <> '' AND soh.lasinvnum_0 <> '' AND
MONTH(soh.shidat_0) = MONTH(getdate()) THEN
(sop.netpri_0 * soq.qty_0 * soh.chgrat_0)
ELSE
0
END) AS invoiced_mtd
FROM x3v6.cicprod.sorder soh
LEFT OUTER JOIN x3v6.cicprod.bpcustomer bpc
ON soh.bpcord_0 = bpc.bpcnum_0
LEFT OUTER JOIN x3v6.cicprod.sorderq soq
ON soh.sohnum_0 = soq.sohnum_0
LEFT OUTER JOIN x3v6.cicprod.sorderp sop
ON soq.sohnum_0 = sop.sohnum_0
AND soq.soplin_0 = sop.soplin_0
AND soq.soqseq_0 = sop.sopseq_0
LEFT OUTER JOIN x3v6.cicprod.itmmaster itm
ON sop.itmref_0 = itm.itmref_0
UNION ALL
SELECT SUM(CASE
WHEN sih.invtyp_0 = 2 AND
MONTH(sih.accdat_0) = MONTH(getdate()) THEN
sid.amtnotlin_0 * (-1)
ELSE
0
END)
FROM x3v6.cicprod.sinvoice sih
LEFT OUTER JOIN x3v6.cicprod.sinvoiced sid
ON sih.num_0 = sid.num_0) x;
Try using a CTE for the UNION query first. Here is a simplified example with the same structure as your query:
;with cteTest AS (
((select 2 as 'test'))
union all
((select 3 as 'test'))
)
select sum(test) from cteTest
I am having difficulty with this. This query worked fine in calculating the sums until I put the first inner join in. In the table tbl_companies there are multiple entries per company, for example the table could look like this:
priority company externalip
1 bla 9.9.9.9
1 bla 3.3.3.3
1 company2 3.56.6.6
In the below query the sum (that calculates As TotalWithoutNew and TotalAllId is doubling when there is more than one entry for the company, and tripling if there is three etc. What I want it to do is simply bring back the priority from the table tbl_companies
SELECT b.company,
b.priority,
i.concom,
Coalesce (SUM(CASE
WHEN c.category_id = '30' THEN 0
ELSE t.logmins
END), 0) AS totalwithoutnew,
Coalesce (SUM(t.logmins), 0) AS totalallid
FROM helpdesk3.dbo.inquiry AS i
INNER JOIN [Check].[dbo].[tbl_companies] AS b
ON i.concom = b.company COLLATE sql_latin1_general_cp1_ci_as
INNER JOIN timelog AS t
ON t.inquiry_id = i.inquiry_id
INNER JOIN prod AS p
ON i.prod_id = p.prod_id
INNER JOIN category AS c
ON p.category_id = c.category_id
WHERE ( Datepart(yyyy, escdate) = 2011 )
GROUP BY i.concom,
b.company,
b.priority
ORDER BY totalwithoutnew DESC,
b.priority DESC
You should split the query to avoid multiple results from tbl_companies.
select distinct b.company,
b.priority,
x.concom,
x.totalwithoutnew,
x.totalallid
FROM (
SELECT i.concom,
Coalesce (SUM(CASE
WHEN c.category_id = '30' THEN 0
ELSE t.logmins
END), 0) AS totalwithoutnew,
Coalesce (SUM(t.logmins), 0) AS totalallid
FROM helpdesk3.dbo.inquiry AS i
INNER JOIN timelog AS t
ON t.inquiry_id = i.inquiry_id
INNER JOIN prod AS p
ON i.prod_id = p.prod_id
INNER JOIN category AS c
ON p.category_id = c.category_id
WHERE ( Datepart(yyyy, escdate) = 2011 )
GROUP BY i.concom
) x
INNER JOIN [Check].[dbo].[tbl_companies] AS b
ON x.concom = b.company COLLATE sql_latin1_general_cp1_ci_as
ORDER BY x.totalwithoutnew DESC,
b.priority DESC
Your join from the INQUIRY table to the tbl_companies table is going to generate a set of three rows (when there are three companies) so the next join to the TIMELOG table is also going to have three values for each TIMELOG.LOGMINS column - therefore it follows that the COALESCE (SUM(CASE WHEN C.CATEGORY_ID = '30' THEN 0 ELSE t.LOGMINS END), 0) AS TotalWithoutNew calculation will be tripled.
select
...
FROM helpdesk3.dbo.INQUIRY AS i
inner join [Check].[dbo].[tbl_companies] As B ON i.CONCOM = B.company COLLATE SQL_Latin1_General_CP1_CI_AS
INNER JOIN TIMELOG AS t ON t.INQUIRY_ID = i.INQUIRY_ID
...
If you want a single company to appear in the select and not multiply up the sum remove the join to tbl_companies from the where clause and the group by clause. Something along these lines should work (although without knowing the exact structure of the data I can't be certain):
select
(select company from [tbl_companies] where company = i.concom) as company,
(select priority from [tbl_companies] where company = i.concom) as priority,
...
FROM helpdesk3.dbo.INQUIRY AS i
INNER JOIN TIMELOG AS t ON t.INQUIRY_ID = i.INQUIRY_ID
...
There are a couple of ways of doing this. Assuming that priority, company and externalip uniquely identify tbl_companies records, I suggest:
SELECT b.company,
b.priority,
i.concom,
Coalesce (SUM(CASE
WHEN c.category_id = '30' THEN 0
ELSE t.logmins
END), 0) / COUNT(DISTINCT b.externalip) AS totalwithoutnew,
Coalesce (SUM(t.logmins), 0) / COUNT(DISTINCT b.externalip) AS totalallid
FROM helpdesk3.dbo.inquiry AS i
INNER JOIN [Check].[dbo].[tbl_companies] AS b
ON i.concom = b.company COLLATE sql_latin1_general_cp1_ci_as
INNER JOIN timelog AS t
ON t.inquiry_id = i.inquiry_id
INNER JOIN prod AS p
ON i.prod_id = p.prod_id
INNER JOIN category AS c
ON p.category_id = c.category_id
WHERE ( Datepart(yyyy, escdate) = 2011 )
GROUP BY i.concom,
b.company,
b.priority
ORDER BY totalwithoutnew DESC,
b.priority DESC
I am trying to display records which are created after Oct 1 2010. But my query doesn't seem to work. It also display records from 2004 - Sept 2010 which is not wanted.
What is wrong with the query below?
select Distinct app.app_id,
(convert(varchar, creation_date,101) + ' ' + convert(varchar,creation_date ,108)) as creation_date,
dbo.oea_fn_get_amc_mem_name(app.app_id,primary_msn,getdate(), 'EN', 30000) PIName,
dbo.oea_fn_get_pid_countyname(app.app_id,primary_msn,'OC')as PIpid,
primary_msn,
zip,
home_tel,
work_tel,
work_extn,
other_contact,
other_ext,
cell_tel,
dbo.oea_fn_get_amc_mem_name(app.app_id,mem.msn,getdate(), 'EN', 30000)as Kname,
dbo.oea_fn_get_pid_countyname(app.app_id,mem.msn,'OC')as Knamepid,
mem.msn as Kmsn,
(select count(reminder_id) from reminders (nolock) where app_id=app.app_id) as reminder
from app_application app (nolock)
inner join app_member mem with (nolock) on app.app_id=mem.app_id
--left outer join Oea_App_Program_Disposition disp with (nolock) on mem.app_id = disp.app_id and mem.msn=disp.msn
inner join app_address aadd with (nolock) on app.app_id=aadd.app_id
--inner join app_calc_results calc with (nolock) on mem.app_id=calc.app_id and calc.msn=mem.msn
left outer join app_member_benefits ben with (nolock) on mem.app_id = ben.app_id and mem.msn=ben.msn
where
isnull(mem.coverage_required,0) = 1
and app.app_status = 's'
and ben.ins_end_date < getdate()
and app.client_id = 30000
and app.app_id not in (select app_id from app_renewal)
and (mem.msn in (select calc.msn from app_calc_results calc
inner join app_application app on calc.app_id = app.app_id and calc.prog_id = 'CK' and calc.opt_out = 1))
and (mem.msn in (select msn from app_calc_results where app_id=app.app_id and status not in ('A','X')))
or (mem.msn in (select msn from Oea_App_Program_Disposition where app_id=app.app_id and disp_status not in ('A','P')) )
and app.creation_date >= '10/01/2010'
Thanks for all the help.
You probably want this:
and (
(mem.msn in (select calc.msn from app_calc_results calc
inner join app_application app on calc.app_id = app.app_id and calc.prog_id = 'CK' and calc.opt_out = 1))
or (mem.msn in (select msn from app_calc_results where app_id=app.app_id and status not in ('A','X')))
or (mem.msn in (select msn from Oea_App_Program_Disposition where app_id=app.app_id and disp_status not in ('A','P')) )
)
and app.creation_date >= '10/01/2010'
The problem is with the logic behind the or in the where clause.
As others have stated, the problem is likely the Or clause in the Where clause. In effect, your query is:
Select ...
From ..
Where (A And B And C
And D And E
And F And G
And app.creation_date >= '10/01/2010'
)
Or mem.msn In (
Select msn
From Oea_App_Program_Disposition
Where app_id=app.app_id
And disp_status not in ('A','P')
)
Thus, if for any row, if the Or is true, the rest of the "Ands" are ignored. I would assume that the Or is supposed to be paired with one of the And clauses.