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
Related
WITH c AS
(SELECT A.QuestionHdrKey AS QuestionHdrKey1,
A.DivisionKey AS DivisionKey1,
COUNT(1) AS QCount
FROM Mobile.QuestionLocationMap A WITH (NOLOCK)
INNER JOIN Mobile.Question b WITH (NOLOCK) ON A.QuestionKey = b.PKey
WHERE A.QuestionHdrKey = 200305685377000000
GROUP BY A.QuestionHdrKey,
A.DivisionKey),
d AS
(SELECT a.QuestionHdrKey,
a.QuestionKey,
a.DivisionKey,
a.InvDate,
a.HdrKey,
ROW_NUMBER() OVER (PARTITION BY a.DivisionKey,
a.invdate,
a.HdrKey
ORDER BY a.QuestionKey) AS RowId
FROM mobile.StatusReport a WITH (NOLOCK)
INNER JOIN mobile.Question b WITH (NOLOCK) ON a.QuestionKey = b.PKey
AND b.QuestionType = 'rate'
AND InputType = 'numeric'
WHERE a.QuestionHdrKey = '200305685377000000'
GROUP BY a.QuestionHdrKey,
a.DivisionKey,
a.HdrKey,
a.InvDate,
a.QuestionKey)
SELECT a.DivisionKey,
a.InvDate AS ModifiedDate,
a.QuestionHdrKey,
a.HdrKey,
COUNT(DISTINCT a.QuestionKey) AS QuestionKey,
SUM(CAST(a.Value AS int)) AS value,
SUM(b.Rate) AS RATE
--case when a.invdate between '2020-05-09' and '2022-03-31' then case when then case when cast(Value as int)*5>5 then 5 else cast(Value as int)*5 end else cast(Value as int) end as value,c.QCount
FROM mobile.StatusReport a WITH (NOLOCK)
INNER JOIN mobile.Question b WITH (NOLOCK) ON a.QuestionKey = b.PKey
AND b.QuestionType = 'rate'
AND InputType = 'numeric'
INNER JOIN c WITH (NOLOCK) ON a.DivisionKey = c.DivisionKey1
INNER JOIN d WITH (NOLOCK) ON a.HdrKey = d.HdrKey
AND a.QuestionKey = d.QuestionKey
WHERE a.QuestionHdrKey = '200305685377000000'
--and a.HdrKey='210305757994230000'
AND d.RowId <= c.QCount
GROUP BY a.DivisionKey,
a.InvDate,
a.QuestionHdrKey,
a.HdrKey,
c.QCount;
I have this table queried in PowerBI which generates the below table:
The SQL is validated successfully in Information Design Tool but when trying to view its values, it shows an error in the code. How do I work around this?
Alright, after figuring out that "with as" doesn't work outside of the select function in the IDS, I've ditched the aliases and used sub-queries.
select HdrKey,a.DivisionKey,InvDate,RowId ,count(b.QuestionKey) as QCount,qCOUNT_,[value],POINT
from
(select distinct a.HdrKey,a.DivisionKey, a.InvDate, ROW_NUMBER() OVER(PARTITION BY QuestionHdrKey, DivisionKey, a.InvDate ORDER BY a.InvDate) AS RowId,
sum(cast([value] as int)) AS [value], COUNT(DISTINCT A.QuestionKey) AS qCOUNT_, SUM(B.Rate) AS POINT
from NominInventory.mobile.StatusReport a with(nolock)
inner join NominInventory.mobile.Question b with(nolock) on a.QuestionKey=b.PKey and B.QuestionType = 'rate' and InputType='numeric'
where a.QuestionHdrKey='200305685377000000'
GROUP BY a.HdrKey,a.DivisionKey, a.InvDate,QuestionHdrKey
) a
inner join NominInventory.Mobile.QuestionLocationMap b with(nolock) on a.DivisionKey=b.DivisionKey and b.QuestionHdrKey = '200305685377000000'
group by HdrKey,a.DivisionKey,InvDate,RowId,qCOUNT_,[value],POINT
having a.RowId<=count(b.QuestionKey)
I've read the threads about loops (pros & cons) in and around a SQL statements. I need to "Loop" through 12 hours, hr by hr and was wondering if there is a better way than "Do-While-Loop, etc.) Here is my SQL...
SELECT R.FinalProd
, MIN(r.seqnumber) Seq
, MIN(S.RollRecID) RID
, COUNT(DISTINCT S.RollRecID) Pieces
, (MIN(r.seqnumber) + COUNT(DISTINCT S.RollRecID) - 1) endd
FROM NYS1Reheat1 R INNER JOIN NYS1SawPieces S ON R.RecordID = S.RollRecID INNER JOIN TensileProducts T ON R.FinalProd = T.SQLProduct
where s.ShiftIdent = '05/22/15154D' and r.Location = 'HISTORY'
and datepart(hour,s.prodtime) > 17 and datepart(hour,s.prodtime) < 19
GROUP BY R.FinalProd, T.FootWeight
order by RID
I need to start at 1700 and go hr by hr to 0600.
My plan, as of now, is to "loop" 12 times through the code.
Thanks,
Doug
You can cross join your time intervals:
;with loop12 as (
select 17 as f, 19 as t union all
select 19 as f, 21 as t union all
...
)
SELECT R.FinalProd
, MIN(r.seqnumber) Seq
, MIN(S.RollRecID) RID
, COUNT(DISTINCT S.RollRecID) Pieces
, (MIN(r.seqnumber) + COUNT(DISTINCT S.RollRecID) - 1) endd
, loop12.f
FROM NYS1Reheat1 R
INNER JOIN NYS1SawPieces S ON R.RecordID = S.RollRecID
INNER JOIN TensileProducts T ON R.FinalProd = T.SQLProduct
CROSS JOIN loop12
WHERE s.ShiftIdent = '05/22/15154D' and r.Location = 'HISTORY'
and datepart(hour,s.prodtime) > loop12.f and datepart(hour,s.prodtime) < loop12.t
GROUP BY R.FinalProd, T.FootWeight
order by RID, loop12.f
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
Hey so my query right now is
ALTER PROCEDURE [SSRS].[VolumeCustomers]
#UserID int
AS
select
CaseTypeName,
COUNT(CaseNo) as CaseCount,
'Open' as indicator
FROM ORDERS.ApCase AC with (NOLOCK)
join ORDERS.CaseType CT (NOLOCK) on CT.CaseTypeID = AC.CaseTypeID
join WORKFLOW.WorkflowHistory WH (NOLOCK) on WH.EntityID = AC.CaseID and TableID = dbo.GetTableID('ApCase', 'ORDERS') and WH.Active = 1
inner join WORKFLOW.WorkflowStep WS (NOLOCK) on WS.WorkflowStepID = WH.WorkflowStepID and WS.NextStepID is null
where (AC.Active =1 and AC.CreatedDate >= DATEADD(day,-7,getdate()) and AC.CreatedDate < GETDATE())
Group By CaseTypeName
union
select
CaseTypeName,
COUNT(Caseno) as CaseCount,
'Closed' as indicator
FROM ORDERS.ApCase AC with (NOLOCK)
join ORDERS.CaseType CT (NOLOCK) on CT.CaseTypeID = AC.CaseTypeID
join WORKFLOW.WorkflowHistory WH (NOLOCK) on WH.EntityID = AC.CaseID and TableID = dbo.GetTableID('ApCase', 'ORDERS') and WH.Active = 1
join WORKFLOW.WorkflowStep WS (NOLOCK) on WS.WorkflowStepID = WH.WorkflowStepID and WS.NextStepID is not null
where (AC.Active =1 and AC.CreatedDate >= DATEADD(day,-7,getdate()) and AC.CreatedDate < GETDATE())
GROUP BY CaseTypeName
Order by CaseCount desc
and the out put is
Cytogenetics 2 All
Cytogenetics 1 Open
Flow Tech 1 All
Flow Tech 1 Open
Surgical 1 All
Surgical 1 Open
But i want the cytogenetics, flow tech, and surgical to all appear on the same row
example:
Cytogenetics 2 All 1 Open
Flow Tech 1 All 1 Open
Surgical 1 All 1 Open
How do I edit my query to reflect this?
Does this work?
SELECT A.*, B.CaseCount, B.indicator
FROM (<First Part of Union in Question>) AS A INNER JOIN
(<Second Part of Union in Question>) AS B ON A.CaseTypeName = B.CaseTypeName
SELECT
CaseTypeName,
COUNT(CASE WHEN WS.NextStepID IS NULL THEN Caseno END) AS CaseCountOpen,
COUNT(CASE WHEN WS.NextStepID IS NOT NULL THEN Caseno END) AS CaseCountClosed,
COUNT(CaseNo) AS CaseCountAll
FROM ORDERS.ApCase AC with (NOLOCK)
JOIN ORDERS.CaseType CT (NOLOCK)
ON CT.CaseTypeID = AC.CaseTypeID
JOIN WORKFLOW.WorkflowHistory WH (NOLOCK)
ON WH.EntityID = AC.CaseID
AND TableID = dbo.GetTableID('ApCase', 'ORDERS')
AND WH.Active = 1
JOIN WORKFLOW.WorkflowStep WS (NOLOCK)
ON WS.WorkflowStepID = WH.WorkflowStepID
WHERE AC.Active = 1
AND AC.CreatedDate >= DATEADD(day,-7,getdate())
AND AC.CreatedDate < GETDATE()
GROUP BY CaseTypeName
ORDER BY CaseCountAll 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.