Getting error with query statement sql server - sql

When I execute the folowing query :
SELECT DISTINCT
dat.FiscalYear,
dat.MonthName As FiscalMonth,
dat.FiscalQuarter,
dat.FiscalSemester,
a.m AS m,
o.oName AS o,
o.Calculation,
o.oDispOrder ,
o.oGrpId
FROM
[V].[dbo].[DimDate] dat
CROSS JOIN
(SELECT
cal.calculation, ltrim(p.oName) As oName,
p.DisplayingOrder as oDispOrder, p.oGrpId
FROM
[V].[dbo].[Reporto] p
CROSS JOIN
(SELECT 'Year to Date' as Calculation
UNION
SELECT 'Current Dim Date' as Calculation
UNION
SELECT 'Previous Year' as Calculation
UNION
SELECT 'Last Year Current Month' as Calculation) cal
CROSS JOIN
(SELECT
ltrim(b.m) As m, b.DisplayingOrder as mDispOrder,
b.Used as used
FROM
[V].[dbo].[ReportBusinessLine] b
WHERE b.used = 1) a
WHERE
(p.used = 1 and p.reportId = 1)) o
WHERE
dat.FiscalYear = 2013
I always got the following error :
Msg 4104, Level 16, State 1, Line 6
The multi-part identifier "a.m" could not be bound.
Many thanks .

Formatted more clearly, your from statement is:
FROM [V].[dbo].[DimDate] dat CROSS JOIN
(SELECT cal.calculation, ltrim(p.oName) As oName, p.DisplayingOrder as oDispOrder, p.oGrpId
FROM [V].[dbo].[Reporto] p CROSS JOIN
(SELECT 'Year to Date' as Calculation UNION
SELECT 'Current Dim Date' as Calculation UNION
SELECT 'Previous Year' as Calculation UNION
SELECT 'Last Year Current Month' as Calculation
) cal CROSS JOIN
(SELECT ltrim(b.m) As m, b.DisplayingOrder as mDispOrder, b.Used as used
FROM [V].[dbo].[ReportBusinessLine] b
WHERE b.used = 1
) a
WHERE (p.used = 1 and p.reportId =1 )
) o
WHERE dat.FiscalYear = 2013
You can clearly see that a is a table alias in a subquery. If you want the field m, then you need to put it at the level of o:
FROM [V].[dbo].[DimDate] dat CROSS JOIN
(SELECT cal.calculation, ltrim(p.oName) As oName, p.DisplayingOrder as oDispOrder, p.oGrpId,
a.m
FROM [V].[dbo].[Reporto] p CROSS JOIN
(SELECT 'Year to Date' as Calculation UNION
SELECT 'Current Dim Date' as Calculation UNION
SELECT 'Previous Year' as Calculation UNION
SELECT 'Last Year Current Month' as Calculation
) cal CROSS JOIN
(SELECT ltrim(b.m) As m, b.DisplayingOrder as mDispOrder, b.Used as used
FROM [V].[dbo].[ReportBusinessLine] b
WHERE b.used = 1
) a
WHERE (p.used = 1 and p.reportId =1 )
) o
WHERE dat.FiscalYear = 2013
And then refer to it as o.m in the select.
Formatting code so it is readable can do wonders for finding and preventing errors.

Try this one -
SELECT DISTINCT
dat.FiscalYear,
dat.monthname AS FiscalMonth,
dat.FiscalQuarter,
dat.FiscalSemester,
o.m AS m, --<--- invalid alias
o.oName AS o,
o.Calculation,
o.oDispOrder,
o.oGrpId
FROM [dbo].[DimDate] dat
CROSS JOIN (
SELECT
cal.calculation,
LTRIM(p.oName) AS oName,
p.DisplayingOrder AS oDispOrder,
p.oGrpId,
a.m --<--- missing in SELECT
FROM [dbo].[Reporto] p
CROSS JOIN (
SELECT 'Year to Date' AS Calculation
UNION ALL
SELECT 'Current Dim Date'
UNION ALL
SELECT 'Previous Year'
UNION ALL
SELECT 'Last Year Current Month'
) cal
CROSS JOIN (
SELECT
LTRIM(b.m) AS m,
b.DisplayingOrder AS mDispOrder,
b.Used AS used
FROM [dbo].[ReportBusinessLine] b
WHERE b.used = 1
) a
WHERE p.used = 1 AND p.reportId = 1
) o
WHERE dat.FiscalYear = 2013

Related

SQL Case When Slowing Down Query

What I'm looking to do is quantify the total value of purchases and the number of months in which a purchase was made within three different timeframes by account. I only want to look at accounts who made a purchase between 1-1-2020 and 4-1-2021.
I'm wondering if there is a more streamlined way to pull in the fields I'm creating using CASE WHEN below (maybe through a series of queries to create the calculations and the left joining?). This query is taking extremely long to pull back, so I'd like to enhance this code where I can. All of my code and desired output is listed below. Thank you!
Creating a temporary table to pull account numbers:
DROP TABLE IF EXISTS #accounts
SELECT DISTINCT s.account_no, c.code, c.code_desc
INTO #accounts
FROM sales AS s
LEFT JOIN customer AS c ON s.account_no = c.account_no
WHERE s.tran_date BETWEEN '2020-01-01' AND '2021-04-01'
GROUP BY s.account_no, c.code, c.code_desc;
Confirming row counts:
SELECT COUNT (*)
FROM #accounts
ORDER BY account_no;
Creating Sales and Sales period count columns for three timeframes:
SELECT
s.account_no, c.code, c.code_desc
SUM(CASE
WHEN s.tran_date BETWEEN '2020-01-01' AND '2021-04-01'
THEN VALUE_USD
END) AS Total_Spend_Pre,
SUM(CASE
WHEN s.tran_date BETWEEN '2021-04-01' AND '2022-03-31'
THEN VALUE_USD
END) Total_Spend_During,
SUM(CASE
WHEN s.tran_date > '2022-04-01'
THEN VALUE_USD
END) Total_Spend_Post,
COUNT(DISTINCT CASE WHEN s.tran_date BETWEEN '2020-01-01' AND '2021-04-01' THEN CONCAT(s.bk_month, s.bk_year) END) Pre_Periods,
COUNT(DISTINCT CASE WHEN s.tran_date BETWEEN '2021-04-01' AND '2022-03-31' THEN CONCAT(s.bk_month, s.bk_year) END) During_Periods,
COUNT(DISTINCT CASE WHEN s.tran_date > '2022-04-01' THEN CONCAT(s.bk_month, s.bk_year) END) Post_Periods
FROM
sales AS s
LEFT JOIN
customer AS c ON s.account_no = c.account_no
WHERE
c.account_no IN (SELECT DISTINCT account_no
FROM #accounts)
GROUP BY
s.account_no, c.code, c.code_desc;
Desired output:
account_no
code
code_desc
Total_Spend_Pre
Total_Spend_During
Total_Spend_Post
Pre_Periods
During_Periods
Post_Periods
25
1234
OTHER
1000
2005
500
2
14
5
11
5678
PC
500
100
2220
5
11
2
You may use your date ranges to join with dataset, and 'Tag' your result like below, this will result in 3 rows, for each group. If you need them in a single row, have PIVOTE over it
;With DateRanges AS (
SELECT CAST('2020-01-01' AS DATE) StartDate, CAST('2021-04-01' AS DATE) EndDate, 'Pre' Tag UNION
SELECT '2021-04-01', '2022-03-31', 'During' UNION
SELECT '2022-04-01', Null, 'Post'
)
SELECT s.account_no, c.code, c.code_desc, d.Tag,
SUM(VALUE_USD) AS Total_Spend,
COUNT(DISTINCT CONCAT(s.bk_month, s.bk_year)) RecordCount
FROM sales as s
LEFT JOIN customer as c
INNER JOIN DateRanges D ON s.tran_date BETWEEN D.StartDate AND ISNULL(D.EndDate,s.tran_date)
ON s.account_no = c.account_no
WHERE c.account_no IN (SELECT DISTINCT account_no FROM #accounts)
GROUP BY s.account_no, c.code, c.code_desc;
with [cte_accountActivityPeriods] as (
select [PeriodOrdinal] = 1, [PeriodName] = 'Total Spend Pre', [PeriodStart] = convert(date,'2020-01-01',23) , [PeriodFinish] = convert(date,'2021-03-31',23) union
select [PeriodOrdinal] = 2, [PeriodName] = 'Total Spend During', [PeriodStart] = convert(date,'2021-04-01',23) , [PeriodFinish] = convert(date,'2022-03-31',23) union
select [PeriodOrdinal] = 3, [PeriodName] = 'Total Spend Post', [PeriodStart] = convert(date,'2022-04-01',23) , [PeriodFinish] = convert(date,'9999-12-31',23)
)
, [cte_allsalesForActivityPeriod]
SELECT s.account_no, bk_month, bk_year, [PeriodOrdinal], s.tran_date, s.value_usd
FROM sales as s
cross join [cte_accountActivityPeriods]
on s.[tran_date] between [cte_ActivityPeriods].[PeriodStart] and [cte_ActivityPeriods].[PeriodFinish]
)
, [cte_uniqueAccounts] as ( /*Unique and qualifying Accounts*/
select distinct account_no from [cte_allsalesForActivityPeriod]
inner join #accounts accs on accs.[account_no] = [cte_allsalesForActivityPeriod].[account_no]
)
, [cte_AllSalesAggregatedByPeriod] as (
select account_no, [PeriodOrdinal], bk_month, bk_year, [PeriodTotalSpend] = sum([value_usd])
from [cte_allsalesForActivityPeriod]
group by s.account_no, [PeriodOrdinal], bk_month, bk_year
)
, [cte_PeriodAnalysis] as (
select account_no, [PeriodOrdinal], [ActivePeriods] = count(distinct concat(bk_month, bk_year))
from [cte_AllSalesAggregatedByPeriod]
group by s.account_no, [PeriodOrdinal]
)
, [cte_pivot_clumsily] as (
/* Aggregations already done - so simple pivot */
select [cte_uniqueAccounts].[account_no]
, [Total_Spend_Pre] = case when [SaleVal].[PeriodOrdinal] in (1) then [SaleVal].[PeriodTotalSpend] else 0 end
, [Total_Spend_During] = case when [SaleVal].[PeriodOrdinal] in (2) then [SaleVal].[PeriodTotalSpend] else 0 end
, [Total_Spend_Post] = case when [SaleVal].[PeriodOrdinal] in (3) then [SaleVal].[PeriodTotalSpend] else 0 end
, [Pre_Periods] = case when [SalePrd].[PeriodOrdinal] in (1) then [SalePrd].[ActivePeriods] else 0 end
, [During_Periods] = case when [SalePrd].[PeriodOrdinal] in (2) then [SalePrd].[ActivePeriods] else 0 end
, [Post_Periods] = case when [SalePrd].[PeriodOrdinal] in (3) then [SalePrd].[ActivePeriods] else 0 end
from [cte_uniqueAccounts]
left join [cte_AllSalesAggregatedByPeriod] [SaleVal] on [SaleVal].[account_no] = [cte_uniqueAccounts].[account_no]
left join [cte_PeriodAnalysis] [SalePrd] on [SalePrd].[account_no] = [cte_uniqueAccounts].[account_no]
)
select c.code, c.code_desc, [cte_pivot_clumsily].*
from [cte_pivot_clumsily]
LEFT JOIN customer as c
ON [cte_pivot_clumsily].account_no = c.account_no

display records for first day from selcted date range and end date from selected date range.Date range could be any date

I need to show open and close stock for a user input date range.
For open stock it should take the stock in first day from selected date range and close stock it should take stock in end date from selected date range.
Let say I have data from 3rd Jan. to 30th Jan. (in database) and user has selected date range (1st Jan. to 31st Jan.) so in open stock it should display stock for 3rd Jan. and in close stock it should display stock for 30th Jan.
How can I do this in SAP HANA Studio?
making a guess on how your source data look. I made an attempt to solve your problem.
with data as (
--here are some example data
select to_date('2019-12-31','yyyy-mm-dd') d ,-1 stock from dual union all
select to_date('2020-01-03','yyyy-mm-dd') d ,1 stock from dual union all
select to_date('2020-01-04','yyyy-mm-dd') d ,2 stock from dual union all
select to_date('2020-01-30','yyyy-mm-dd') d ,3 stock from dual union all
select to_date('2020-02-01','yyyy-mm-dd') d ,2 stock from dual
)
,filt_data as (
select * from data
where d between to_date('2020-01-01','yyyy-mm-dd') and to_date('2020-01-31','yyyy-mm-dd')
)
, min_date as(
select min(d) d from filt_data
)
, max_date as(
select max(d) d from filt_data
)
select (select d from filt_data where d = (select d from min_date)) open_stock_date
,(select stock from filt_data where d = (select d from min_date)) open_stock
,(select d from filt_data where d = (select d from max_date)) close_stock_date
,(select stock from filt_data where d = (select d from max_date)) close_stock
from dual ;
The following query might do what you are looking for :
SELECT
MAX(CASE WHEN S.dateStock = DT.minDate THEN S.dateStock END) AS openDate,
MAX(CASE WHEN S.dateStock = DT.minDate THEN S.value END) AS openStock,
MAX(CASE WHEN S.dateStock = DT.maxDate THEN S.dateStock END) AS closeDate,
MAX(CASE WHEN S.dateStock = DT.maxDate THEN S.value END) AS closeStock
FROM
stock S
JOIN(
SELECT
min(dateStock) as minDate,
max(dateStock) as maxDate
FROM stock
WHERE dateStock BETWEEN '2020-01-01' AND '2020-01-31'
) DT ON S.dateStock = DT.minDate OR S.dateStock = DT.maxDate
SEE DEMO HERE

I am unable to use group by in nested query of ms access

I am facing problem in using nested queries in MS access. Those queries are working fine in sql developer.
Access SQL:-
select
B.prDate,
B.Month,
(select C.Entity_Id,avg(C.prclose)
from **B** as C
where C.Month>=B.Month
and C.Month <= B.Month+3
group by C.Entity_Id)
from (
select A.Entity_Id, A.prDate, A.prclose ,
(
(SELECT max(ID)
FROM sheet1 where Entity_Id=A.Entity_Id
) -
(SELECT ID
FROM sheet1 where ID=A.Id) +1
) as Month
from sheet1 as A
order by Month, A.Entity_Id asc
) B
Or
you can replace above alias with below query
select B.prDate, B.Month , ((select C.Entity_Id,avg(C.prclose) from
(select A.Entity_Id,A.prDate,A.prclose , ((SELECT max(ID) FROM sheet1 where Entity_Id=A.Entity_Id ) - (SELECT ID FROM sheet1 where ID=A.Id ) +1) as Month from sheet1 as A order by Month, A.Entity_Id asc) B as C where C.Month>=B.Month and C.Month <= B.Month+3 group by C.Entity_Id ))
from
(select A.Entity_Id,A.prDate,A.prclose , ((SELECT max(ID) FROM sheet1 where Entity_Id=A.Entity_Id ) - (SELECT ID FROM sheet1 where ID=A.Id ) +1) as Month from sheet1 as A order by Month, A.Entity_Id asc) B
Other SQL:-
select B.prDate, B.Month , (select C.Entity_Id,avg(C.prclose) from B) as C where C.Month>=B.Month and C.Month <= B.Month+3 group by C.Entity_Id from
(select A.Entity_Id,A.prDate,A.prclose , ((SELECT max(ID) FROM sheet1 where Entity_Id=A.Entity_Id ) - (SELECT ID FROM sheet1 where ID=A.Id ) +1) as Month from sheet1 as A order by Month, A.Entity_Id asc) B
In SELECT clause subqueries, you cannot return more than one field as you attempt with aggregate query. To resolve, because you need to reuse B, consider saving this resultset in an intermediate, external query and reference it in a final query:
Intermediate Query (save as MS Access query object; last nested SELECT is redundant)
SELECT A.Entity_Id, A.prDate, A.prclose,
((SELECT MAX(sub.ID)
FROM sheet1 sub
WHERE sub.Entity_Id = A.Entity_Id) - sub.ID) + 1 AS [Month]
FROM sheet1 as A
Final Query
SELECT q.Entity_Id, q.prDate, q.[Month],
(SELECT AVG(sub_q.prclose)
FROM mySavedQuery AS sub_q
WHERE sub_q.Entity_Id = q.Entity_Id
AND sub_q.[Month] >= q.[Month]
AND sub_q.[Month] <= q.[Month] + 3
) AS Avg_PrClose
FROM mySavedQuery AS q
ORDER BY q.[Month], q.Entity_Id
When the day comes when MS Access SQL supports CTE (or you upsize to an enterprise RDBMS), you can turn the saved query object into WITH clause for one statement:
WITH mySavedQuery AS
(SELECT A.Entity_Id, A.prDate, A.prclose,
((SELECT MAX(sub.ID)
FROM sheet1 sub
WHERE sub.Entity_Id = A.Entity_Id) - sub.ID) + 1 AS [Month]
FROM sheet1 as A)
SELECT q.Entity_Id, q.prDate, q.[Month],
(SELECT AVG(sub_q.prclose)
FROM mySavedQuery AS sub_q
WHERE sub_q.Entity_Id = q.Entity_Id
AND sub_q.[Month] >= q.[Month]
AND sub_q.[Month] <= q.[Month] + 3
) AS Avg_PrClose
FROM mySavedQuery AS q
ORDER BY q.[Month], q.Entity_Id

Selecting the Max Date From Multiple Tables

any help would be so incredibly appreciated. I am trying to select the last activity date from a group of tables. The tables include Entry Date, Note date, payment date, and Claim Date. I would like to return only the max value from all these dates. Furthermore I only want records where there has been no activity for over 45 days. I am currently using the following SQL to bring all the dates in then using calculated fields in EXCEL to figure the rest out. Is it possible to do this all with SQL?
Thanks in advance.
SELECT xrxTrnLgr.PatId, xrxTrnLgr.Balance,
Max(xrxPatNotes.NoteDate) AS 'Max of NoteDate',
Max(xrxTrnIcf.PostDate) AS 'Max of IcfPostDate',
Max(xrxPat.EntryDate) AS 'Entry Date',
Max(xrxPat.Coverage) AS 'Coverage',
Max(xrxTrnPay.PostDate) AS 'Last Payment'
FROM xrxTrnLgr
LEFT OUTER JOIN xrxPatNotes ON xrxTrnLgr.PatId = xrxPatNotes.PatId
LEFT OUTER JOIN xrxTrnIcf ON xrxTrnLgr.PatId = xrxTrnIcf.PatId
LEFT OUTER JOIN xrxPat ON xrxTrnLgr.PatId = xrxPat.PatId
LEFT OUTER JOIN xrxTrnPay ON xrxTrnLgr.PatId = xrxTrnPay.PatId
GROUP BY xrxTrnLgr.PatId, xrxTrnLgr.Balance
HAVING (xrxTrnLgr.Balance>$.01)
I think this might do it all in SQL:
select t.patid, t.balance,
max(case when which = 'note' then thedate end) as note,
max(case when which = 'post' then thedate end) as post,
max(case when which = 'entry' then thedate end) as entry,
max(case when which = 'coverage' then thedate end) as coverage,
max(case when which = 'lastPayment' then thedate end) as lastPayment
from xrxTrnLgr t left join
((select patid, notedate as thedate, 'note' as which
from xrxPatNotes
) union all
(select patid, postdate, 'post'
from xrxtrnIcf
) union all
(select patid, EntryDate, 'entry'
from xrxPat
) union all
(select paid, Coverage, 'coverage'
from xrxPat.Coverage
) union all
(select patid, PostDate, 'LastPayment'
from xrxTrnPay.PostDate
)
) d
on t.patid = d.patid
group by t.patid, t.balance
having min(now() - thedate) >= 45

SQL Query in CRM Report

A "Case" in CRM has a field called "Status" with four options.
I'm trying to
build a report in CRM that fills a table with every week of the year (each row is a different week), and then counts the number of cases that have each Status option (the columns would be each of the Status options).
The table would look like this
Status 1 Status 2 Status 3
Week 1 3 55 4
Week 2 5 23 5
Week 3 14 11 33
So far I have the following:
SELECT
SUM(case WHEN status = 1 then 1 else 0 end) Status1,
SUM(case WHEN status = 2 then 1 else 0 end) Status2,
SUM(case WHEN status = 3 then 1 else 0 end) Status3,
SUM(case WHEN status = 4 then 1 else 0 end) Status4,
SUM(case WHEN status = 5 then 1 else 0 end) Status5
FROM [DB].[dbo].[Contact]
Which gives me the following:
Status 1 Status 2 Status 3
2 43 53
Now I need to somehow split this into 52 rows for the past year and filter these results by date (columns in the Contact table). I'm a bit new to SQL queries and CRM - any help here would be much appreciated.
Here is a SQLFiddle with my progress and sample data: http://sqlfiddle.com/#!2/85b19/1
Sounds like you want to group by a range. The trick is to create a new field that represents each range (for you one per year) and group by that.
Since it also seems like you want an infinite range of dates, marc_s has a good summary for how to do the group by trick with dates in a generic way: SQL group by frequency within a date range
So, let's break this down:
You want to make a report that shows, for each contact, a breakdown, week by week, of the number of cases registered to that contact, which is divided into three columns, one for each StateCode.
If this is the case, then you would need to have 52 date records (or so) for each contact. For calendar like requests, it's always good to have a separate calendar table that lets you query from it. Dan Guzman has a blog entry that creates a useful calendar table which I'll use in the query.
WITH WeekNumbers AS
(
SELECT
FirstDateOfWeek,
-- order by first date of week, grouping calendar year to produce week numbers
WeekNumber = row_number() OVER (PARTITION BY CalendarYear ORDER BY FirstDateOfWeek)
FROM
master.dbo.Calendar -- created from script
GROUP BY
FirstDateOfWeek,
CalendarYear
), Calendar AS
(
SELECT
WeekNumber =
(
SELECT
WeekNumber
FROM
WeekNumbers WN
WHERE
C.FirstDateOfWeek = WN.FirstDateOfWeek
),
*
FROM
master.dbo.Calendar C
WHERE
CalendarDate BETWEEN '1/1/2012' AND getutcdate()
)
SELECT
C.FullName,
----include the below if the data is necessary
--Cl.WeekNumber,
--Cl.CalendarYear,
--Cl.FirstDateOfWeek,
--Cl.LastDateOfWeek,
'Week: ' + CAST(Cl.WeekNumber AS VARCHAR(20))
+ ', Year: ' + CAST(Cl.CalendarYear AS VARCHAR(20)) WeekNumber
FROM
CRM.dbo.Contact C
-- use a cartesian join to produce a table list
CROSS JOIN
(
SELECT
DISTINCT WeekNumber,
CalendarYear,
FirstDateOfWeek,
LastDateOfWeek
FROM
Calendar
) Cl
ORDER BY
C.FullName,
Cl.WeekNumber
This is different from the solution Ben linked to because Marc's query only returns weeks where there is a matching value, whereas you may or may not want to see even the weeks where there is no activity.
Once you have your core tables of contacts split out week by week as in the above (or altered for your specific time period), you can simply add a subquery for each StateCode to see the breakdown in columns as in the final query below.
WITH WeekNumbers AS
(
SELECT
FirstDateOfWeek,
WeekNumber = row_number() OVER (PARTITION BY CalendarYear ORDER BY FirstDateOfWeek)
FROM
master.dbo.Calendar
GROUP BY
FirstDateOfWeek,
CalendarYear
), Calendar AS
(
SELECT
WeekNumber =
(
SELECT
WeekNumber
FROM
WeekNumbers WN
WHERE
C.FirstDateOfWeek = WN.FirstDateOfWeek
),
*
FROM
master.dbo.Calendar C
WHERE
CalendarDate BETWEEN '1/1/2012' AND getutcdate()
)
SELECT
C.FullName,
--Cl.WeekNumber,
--Cl.CalendarYear,
--Cl.FirstDateOfWeek,
--Cl.LastDateOfWeek,
'Week: ' + CAST(Cl.WeekNumber AS VARCHAR(20)) +', Year: ' + CAST(Cl.CalendarYear AS VARCHAR(20)) WeekNumber,
(
SELECT
count(*)
FROM
CRM.dbo.Incident I
INNER JOIN CRM.dbo.StringMap SM ON
I.StateCode = SM.AttributeValue
INNER JOIN
(
SELECT
DISTINCT ME.Name,
ME.ObjectTypeCode
FROM
CRM.MetadataSchema.Entity ME
) E ON
SM.ObjectTypeCode = E.ObjectTypeCode
WHERE
I.ModifiedOn >= Cl.FirstDateOfWeek
AND I.ModifiedOn < dateadd(day, 1, Cl.LastDateOfWeek)
AND E.Name = 'incident'
AND SM.AttributeName = 'statecode'
AND SM.LangId = 1033
AND I.CustomerId = C.ContactId
AND SM.Value = 'Active'
) ActiveCases,
(
SELECT
count(*)
FROM
CRM.dbo.Incident I
INNER JOIN CRM.dbo.StringMap SM ON
I.StateCode = SM.AttributeValue
INNER JOIN
(
SELECT
DISTINCT ME.Name,
ME.ObjectTypeCode
FROM
CRM.MetadataSchema.Entity ME
) E ON
SM.ObjectTypeCode = E.ObjectTypeCode
WHERE
I.ModifiedOn >= Cl.FirstDateOfWeek
AND I.ModifiedOn < dateadd(day, 1, Cl.LastDateOfWeek)
AND E.Name = 'incident'
AND SM.AttributeName = 'statecode'
AND SM.LangId = 1033
AND I.CustomerId = C.ContactId
AND SM.Value = 'Resolved'
) ResolvedCases,
(
SELECT
count(*)
FROM
CRM.dbo.Incident I
INNER JOIN CRM.dbo.StringMap SM ON
I.StateCode = SM.AttributeValue
INNER JOIN
(
SELECT
DISTINCT ME.Name,
ME.ObjectTypeCode
FROM
CRM.MetadataSchema.Entity ME
) E ON
SM.ObjectTypeCode = E.ObjectTypeCode
WHERE
I.ModifiedOn >= Cl.FirstDateOfWeek
AND I.ModifiedOn < dateadd(day, 1, Cl.LastDateOfWeek)
AND E.Name = 'incident'
AND SM.AttributeName = 'statecode'
AND SM.LangId = 1033
AND I.CustomerId = C.ContactId
AND SM.Value = 'Canceled'
) CancelledCases
FROM
CRM.dbo.Contact C
CROSS JOIN
(
SELECT
DISTINCT WeekNumber,
CalendarYear,
FirstDateOfWeek,
LastDateOfWeek
FROM
Calendar
) Cl
ORDER BY
C.FullName,
Cl.WeekNumber