I am trying to add a Total line at the bottom of this sql syntax but thus far have received no break through. I have viewed the following but both of them do not adhere with my condition. Can someone please provide assistance with regards to this.
Add a summary row with totals
Adding a total row to the end of query result
select dm.Builder ||' ('|| dm.Lot_Size || '''s)' as"Builder",count(sd.Address) "The Count",
dm."Construction_ID"
from input dm
left join data sd on sd.inputfk = dm.inputpk
and sd.Closing Date >= DATE '01/01/2017' and sd.Closing Date < DATE '06/30/2017'
where dm.Construction_ID = 'AJR'
group by dm.Builder,dm.Lot_Size, dm.Project_ID
having count(sd.Address) > 0
order by dm.Builder
When I run it:
Builder The Count Construction_ID
Jake's Homes (55's) 2 AJR
Jake's Homes (65's) 3 AJR
Maggie's Homes (65's) 5 AJR
Maggie's Homes (66's) 2 AJR
Maggie's Homes (75's) 3 AJR
Maggie's Homes (90's) 1 AJR
Total ----------> 16
Your group by has dm.Project_ID, sd.Address which is probably causing it.
For total, you can use ROLLUP:
Try this:
select coalesce(dm.Builder || ' (' || dm.Lot_Size || '''s)', 'Total') as "Builder",
count(sd.Address) "The Count",
dm."Construction_ID"
from input dm
left join data sd on sd.inputfk = dm.inputpk
and sd.Closing date >= date '01/01/2017'
and sd.Closing date < date '06/30/2017'
where dm.Construction_ID = 'AJR'
group by rollup(dm.Builder || ' (' || dm.Lot_Size || '''s)')
having count(sd.Address) > 0
order by "Builder"
Try this:
select dm.Builder ||' ('|| dm.Lot_Size || '''s)' as"Builder",count(sd.Address) "The Count",
dm."Construction_ID"
from input dm
left join data sd on sd.inputfk = dm.inputpk
and sd.Closing Date >= DATE '01/01/2017' and sd.Closing Date < DATE '06/30/2017'
where dm.Construction_ID = 'AJR'
group by rollup( (dm.Builder,dm.Lot_Size, dm.Project_ID) )
having count(sd.Address) > 0
order by dm.Builder
Just... why you need count(sd.Address) > 0 ?
Given the post is tagged with postgresql, assuming it is for that platform; as such, see https://www.postgresql.org/docs/9.5/static/queries-table-expressions.html#QUERIES-GROUPING-SETS
Related
I am trying to return the foretasted value per item, per warehouse, per day and then add them up for the week. I am pulling from two tables depending on the demand date, but the issue is that both tables have a "creation_date" column with timestamps, so it's creating multiple raw_forecast entries per warehouse/item/day when I only want one. I tried to join on the creation dates, but because each table has different timestamps on the creation dates, SQL is returning both forecast quantities of that day. I just want whatever the largest forecast amount was for the day. Any help is so appreciated!
output columns: demand_date, item, fulfillment center, type quantity, raw_forecasts
there are multiple quantities and raw_forecast rows
SELECT
DISTINCT d.demand_date,
d.item,
r.fulfillment_center_external_id,
d.type,
d.quantity,
CASE WHEN d.type IN ('RAW') THEN MAX(DISTINCT d.quantity) ELSE 0 END as Raw_Forecast
FROM
f3_rsc.fab_reporting_demand_forecasts d
Left join f3_rsc.runs r on d.output_id = r.output_id
and TRUNC(d.creation_date) = TRUNC(r.creation_date)
where
1 = 1
and d.demand_date between to_date('{RUN_DATE_YYYY-MM-DD}', 'YYYY-MM-DD') + 11
and to_date('{RUN_DATE_YYYY-MM-DD}', 'YYYY-MM-DD') + 17
and d.type in ('RAW')
and requester_id = 'SWF-PRODUCTION'
and po_placement_status = 'SHOULD_CUT_PO'
and TRUNC(d.creation_date) > to_date('{RUN_DATE_YYYY-MM-DD}', 'YYYY-MM-DD') -3
GROUp BY
1,2,3,4,5
You are getting multiple rows because you are grouping on quantity and the quantities are different. Based on your description stop grouping on quantity (5 in your group by list) and take the MAX() of quantity in your select line. (You also don't need DISTINCT if the column is in the group by list.)
SELECT
d.demand_date,
d.item,
r.fulfillment_center_external_id,
d.type,
MAX(d.quantity),
CASE WHEN d.type IN ('RAW') THEN MAX(DISTINCT d.quantity) ELSE 0 END as Raw_Forecast
FROM
f3_rsc.fab_reporting_demand_forecasts d
Left join f3_rsc.runs r on d.output_id = r.output_id
and TRUNC(d.creation_date) = TRUNC(r.creation_date)
where
1 = 1
and d.demand_date between to_date('{RUN_DATE_YYYY-MM-DD}', 'YYYY-MM-DD') + 11
and to_date('{RUN_DATE_YYYY-MM-DD}', 'YYYY-MM-DD') + 17
and d.type in ('RAW')
and requester_id = 'SWF-PRODUCTION'
and po_placement_status = 'SHOULD_CUT_PO'
and TRUNC(d.creation_date) > to_date('{RUN_DATE_YYYY-MM-DD}', 'YYYY-MM-DD') -3
GROUp BY
1,2,3,4
Let me know if I have misread your situation.
Newbie here. Thanking you in advance for your help!
I have the following code to count unique records based on 3 data elements:
count(distinct concat(a.emp_nbr, b.acct_nbr, c.event_dt))
The event_dt is stored in the db as [DATE].
the issue is that i don't want to EXCLUDE 'DD' in the concat match statement. I want to match based on the MM/YYYY only. I believe the answer is to convert the [DATE] to MM/YYYY.
Ultimately i want to count distinct records based on emp_nbr, acct_nbr and mm/yyyy of event_dt.
Thanks!
MODIFIED
here is the query:
select distinct
B.emp_nbr, A.cust_nbr, E.cntry_enti_nbr, A.event_dt,
count(distinct concat(B.emp_nbr, E.cntry_enti_nbr, A.event_dt))
from customer A
left join user_profile B on A.owner_ID = B.owner_ID
left join account_owner E on A.cust_nbr = E.cust_nbr
where CAST(A.ramp_dt AS date format 'MM/DD/YYYY') between '01/01/2020' and '08/31/2020'
group by 1,2,3,4
Here's a sample of the results that are returned:
ln...emp_nbr.....cust_nbr.....ctry_enti_nbr event_dt......'Unique Identifier'
1....123.........87543290......488807........5/15/2020.........1
2....123.........62524497......488807........2/28/2020.........1 **
3....123.........62524497......488807........2/26/2020.........1 **
4....789.........62524497......488807........2/26/2020.........1
5....876.........62524497......488807........2/26/2020.........1
Line 2 or 3 should NOT be flagged as '1' (unique)
EDIT: changed code based on dnoeth's reco to add the count(*) OVER (PARTITION):
select distinct
B.emp_nbr, A.cust_nbr, E.cntry_enti_nbr, A.event_dt,
to_char(A.event_dt, 'YYYYMM') as Event_Month,
case when COUNT(*) OVER (PARTITION BY B.emp_nbr, A.cntry_enti_nbr, Event_Month)
= 1 then 1 else 0 end as Unique_Monthly_Event
from customer A
left join user_profile B on A.owner_ID = B.owner_ID
left join account_owner E on A.cust_nbr = E.cust_nbr
where CAST(A.event_dt AS date format 'MM/DD/YYYY') between '01/01/2020' and '08/31/2020'
group by 1,2,3,4
works fine for the previous case, however in another case it shows all ZERO for unique:
ln...emp_nbr.....cust_nbr.....ctry_enti_nbr event_dt......'Unique Identifier'
1....123.........78473466......863429........5/31/2020.........0
2....123.........78473466......863429........5/29/2020.........0
3....123.........78473466......863429........5/5/2020..........0
I would like to see ONE record with a unique identifier of "1"
Line 2 or 3 should NOT be flagged as '1' (unique)
... because there's more than one row per emp_nbr/cust_nbr/ctry_enti_nbr?
Then you need a simple Group Count:
select
B.emp_nbr, A.cust_nbr, E.cntry_enti_nbr, A.event_dt,
-- I would like to see ONE record with a unique identifier of "1"
-- this returns the row with the latest event date
case
when row_number()
over (partition by B.emp_nbr, A.cust_nbr, E.cntry_enti_nbr
order by event_dt desc) = 1
then 1
else 0
end
from customer A
left join user_profile B on A.owner_ID = B.owner_ID
left join account_owner E on A.cust_nbr = E.cust_nbr
where CAST(A.ramp_dt AS date format 'MM/DD/YYYY') between '01/01/2020' and '08/31/2020'
group by 1,2,3,4
You can simply use EXTRACT() function to extract year and month from the date. For example:
SELECT COUNT(DISTINCT CONCAT(a.emp_nbr, b.acct_nbr, EXTRACT(YEAR FROM c.event_dt), EXTRACT(MONTH FROM c.event_dt)))
FROM ...
You can use to_char(). Something like this:
count(distinct concat(a.emp_nbr, '|', b.acct_nbr, '|', to_char(c.event_dt, 'YYYYMM'))
or more commonly:
count(distinct a.emp_nbr || '|' || b.acct_nbr || '|' || to_char(c.event_dt, 'YYYYMM')
Note that this also puts a delimiter between
Your query looks off. I think you just want:
select A.cust_nbr, E.cntry_enti_nbr, to_char(c.event_dt, 'YYYYMM'),
count(*)
from customer A left join
user_profile B
on A.owner_ID = B.owner_ID left join
account_owner E
on A.cust_nbr = E.cust_nbr
where CAST(A.ramp_dt AS date format 'MM/DD/YYYY') between '01/01/2020' and '08/31/2020'
group by A.cust_nbr, E.cntry_enti_nbr, to_char(c.event_dt, 'YYYYMM');
I need to simplify a complex old query in order to filter is with date range.
I got a table with Tickets and TicketNotes.
I need
a column with the Tickets count of the day
a column with the Tickets count with a specific note of the day
the date
The old query
SELECT SUM(IFNULL(qtickets.count, 0)) j, SUM(IFNULL(mtickets.count, 0)) m FROM (
SELECT
COUNT(tickets.id) COUNT,
DATE(tickets.date) DATE
FROM
tickets
WHERE
tickets.status = 'Closed' AND tickets.did = 7
AND MONTH(tickets.date) = MONTH( CURRENT_DATE - INTERVAL 1 MONTH )
AND YEAR(tickets.date) = YEAR( CURRENT_DATE - INTERVAL 1 MONTH )
GROUP BY
DATE(tickets.date)
) AS mtickets LEFT JOIN (
SELECT
1 AS COUNT,
DATE(tickets.date) DATE
FROM
ticketnotes
INNER JOIN tickets ON tickets.id = ticketnotes.ticketid
WHERE
ticketnotes.message LIKE '%https://xxxxx.net/help/tickets/%'
AND tickets.status = 'Closed'
AND tickets.did = 7
AND MONTH(tbltickets.date) = MONTH( CURRENT_DATE - INTERVAL 1 MONTH )
AND YEAR(tbltickets.date) = YEAR( CURRENT_DATE - INTERVAL 1 MONTH )
GROUP BY
DATE(tickets.date)
) AS qtickets ON (mtickets.date = qtickets.date)
The goal is to get a result of
Date | M | Q
===================
2020-04-01 | 1 | 1
2020-04-02 | 2 | 1
2020-04-03 | 5 | 2
...
2020-04-30 | 3 | 0
With M be the total closed tickets of the day for did = 7 and Q be the total closed tickets that got the note.message.
I need to check the query with one instance of date filter date BETWEEN '2020-04-01' AND '2020-04-30' and still get the correct three columns.
=======
UPDATE:
When I'm trying to add AND DATE(tickets.date) BETWEEN DATE('2020-04-01') AND DATE('2020-04-30') in Gordon's answer, I got other result data from my primary query.
QUERY:
SELECT
DATE(t.date),
COUNT(t.id) AS num_tickets,
(CASE WHEN COUNT(tn.ticketid) = 0 THEN 0 ELSE 1 END) AS num_with_message
FROM
tickets t
LEFT JOIN ticketnotes tn ON
tn.ticketid = t.id AND tn.message LIKE '%https://xxxxx.net/help/tickets/%'
WHERE
t.status = 'Closed' AND t.did = 7
AND DATE(t.date) BETWEEN DATE('2020-04-01') AND DATE('2020-04-30')
GROUP BY
DATE(t.date)
The result is getting num_tickets with wrong data as getting num_ticket without JOIN.
Any suggestions ?
You could try using case for the ehere like
SELECT
DATE(tickets.date) DATE
, COUNT(tickets.id) M
, case sum( ticketnotes.message LIKE '%https://xxxxx.net/help/tickets/%' <> 0 ) then 1 else null end Q
FROM
ticketnotes
INNER JOIN tickets ON tickets.id = ticketnotes.ticketid
WHERE tickets.status = 'Closed'
AND tickets.did = 7
AND MONTH(tbltickets.date) = MONTH( CURRENT_DATE - INTERVAL 1 MONTH )
AND YEAR(tbltickets.date) = YEAR( CURRENT_DATE - INTERVAL 1 MONTH )
GROUP BY DATE(tickets.date)
This answers the original version of the question.
What you are describing sounds like a group by with left join. However, it is not clear what exactly you are looking for. My best guess is:
select date(t.date), count(t.id) as num_tickets,
count(tn.ticketid) as num_with_message
from tickets t left join
ticketnotes tn
on tn.ticketid = t.id and
tn.message like '%https://xxxxx.net/help/tickets/%'
where t.status = 'Closed' and
t.did = 7
group by date(t.date)
I am kind of stuck in one of the SQL queries where I would require little help.
Table structure is as follow:
Table #1: PROD_ORDER:
ID_PROD_ORDER(PK)
1001
1002
1003
Table #2: JOB
ID_JOB | ID_PROD_ORDER(FK)|ID_ASSET | DT_START | DT_END
1 1001 8 2016/11/22 05:45:50 2016/11/24 13:13:14
2 1001 8 some date some date
3 1002 9 some date some date
4 1002 9 some date some date
5 1003 8 some date some date
6 1001 8 some date some date
Table #3: Confirmation
ID_CONFIRMATION | ID_JOB | QT_CONF | QT_SCRAP
Table #4: DOWNTIME
ID_DOWNTIME | DT_START | DT_END | ID_ORG_SUB_ASSET
Now the requirement is to find order and
Start date of the order (which will be Min of DT_START from JOB)
End date of the order (which will be Max of DT_END from JOB)
Sum of all of its jobs' QT_CONF
Sum of all of its jobs' QT_SCRAP
Downtime from DOWNTIME table where downtime = Difference in seconds of DT_START - DT_END
ID_ASSET, Start Date and End Date will be passed in as parameters.
I have written this query:
SELECT
PO.ID_PROD_ORDER,
J.ID_ORG_ASSET,
SUM(C.QT_CONF) AS "QT_CONF",
SUM(C.QT_SCRAP) AS "QT_SCRAP",
MIN(J.DT_JOB_ST) AS "START_DATE",
MAX(J.DT_JOB_ED) AS "END_DATE",
(SELECT SUM(datediff(ss, D.DT_START, D.DT_END)) AS "DOWNTIMESECONDS"
FROM DOWNTIME D
INNER JOIN SUB_ASSET SA ON D.ID_SUB_ASSET = SA.ID_SUB_ASSET
WHERE SA.ID_ASSET = [Param.3] AND D.DT_START >= J.DT_JOB_ST
AND D.DT_END <= J.DT_JOB_ED)
FROM
PROD_ORDER PO
INNER JOIN
JOB J ON PO.ID_PROD_ORDER = J.ID_PROD_ORDER
AND J.DT_JOB_ST >= '[Param.1]'
AND J.DT_JOB_ED <= '[Param.2]'
LEFT OUTER JOIN
CONFIRMATION C ON C.ID_JOB = J.ID_JOB
WHERE
J.ID_ASSET = [Param.3]
GROUP BY
PO.ID_PROD_ORDER, J.ID_ASSET
The query throws an error:
JOB.DT_JOB_ST cannot be included in select list as it is not used in aggregation or GROUP BY
If I put JOB.DT_JOB_ST and JOB.DT_JOB_ED in GROUP BY, then it returns more than 1 row for each order but I need only one row per order.
How can I correct it? I'm just confused !!
Thanks !
I suspect the issue here is the correlated query, which will try to evaluate for each row - as this includes the DT_JOB_ST and DT_JOB_ED it would need these to be part of the group.
The other option would be to rewrite to not need the correlated query, so something like this should be good for you:
SELECT PO.ID_PROD_ORDER,
J.ID_ORG_ASSET,
SUM(C.QT_CONF) AS [QT_CONF],
SUM(C.QT_SCRAP) AS [QT_SCRAP],
MIN(J.DT_JOB_ST) AS [START_DATE],
MAX(J.DT_JOB_ED) AS [END_DATE],
SUM(ISNULL(datediff(ss, D.DT_START, D.DT_END),0)) AS [DOWNTIMESECONDS]
FROM PROD_ORDER PO
INNER JOIN JOB J
ON PO.ID_PROD_ORDER = J.ID_PROD_ORDER
AND J.DT_JOB_ST >= '[Param.1]'
AND J.DT_JOB_ED <= '[Param.2]'
LEFT JOIN CONFIRMATION C
ON C.ID_JOB = J.ID_JOB
LEFT JOIN DOWNTIME D
INNER JOIN SUB_ASSET SA
ON D.ID_SUB_ASSET = SA.ID_SUB_ASSET
AND SA.ID_ASSET = [Param.3]
ON D.DT_START >= J.DT_JOB_ST
AND D.DT_END <= J.DT_JOB_ED
WHERE J.ID_ASSET = [Param.3]
GROUP BY PO.ID_PROD_ORDER, J.ID_ORG_ASSET
(if you prefer, a CTE could work, too)
Following query worked :
SELECT
PO.ID_PROD_ORDER,
J.ID_ASSET,
SUM(C.QT_CONF) AS "QT_CONF",
SUM(C.QT_SCRAP) AS "QT_SCRAP",
MIN(J.DT_JOB_ST) AS "START_DATE",
MAX(J.DT_JOB_ED) AS "END_DATE",
(SELECT SUM(datediff(ss, D.DT_START, D.DT_END)) AS "DOWNTIMESECONDS"
FROM DOWNTIME D
INNER JOIN SUB_ASSET SA ON D.ID_SUB_ASSET = SA.ID_SUB_ASSET
WHERE SA.ID_ASSET = [Param.3] AND D.DT_START >= MIN(J.DT_JOB_ST)
AND D.DT_END <= MAX(J.DT_JOB_ED))
FROM
PROD_ORDER PO
INNER JOIN
JOB J ON PO.ID_PROD_ORDER = J.ID_PROD_ORDER
AND J.DT_JOB_ST >= '[Param.1]'
AND J.DT_JOB_ED <= '[Param.2]'
LEFT OUTER JOIN
CONFIRMATION C ON C.ID_JOB = J.ID_JOB
WHERE
J.ID_ASSET = [Param.3]
GROUP BY
PO.ID_PROD_ORDER, J.ID_ASSET
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