How to optimize the query which is taking too much time - sql

In this query, i am calling a function "fnGetPoolWinner" in the below query 2-3 times,
which i think slows down its performance or multiple case statements is the reason.
It takes time around 00:01:39.
I have tried options like creating indxes in the table and creating Common Table Expression and then using that query, but haven't found any solution to reduce it's time.
DECLARE #TournamentId INT = 1
DECLARE #TournamentName AS NVARCHAR(MAX)
SELECT #TournamentName = TournamentName FROM Tournaments WHERE TournamentId = #TournamentId
SELECT
(SELECT CustomerIds FROM DBO.fnGetPoolWinner(SET_1.BracketBettingAmount,#TournamentId,
(CASE
WHEN SET_1.GAMES= 63
THEN 1
WHEN SET_1.GAMES= 31
THEN 2
WHEN SET_1.GAMES= 15
THEN 3
ELSE 0
END))) AS [AccountNumber],
#TournamentName AS TournamentName,
(CASE
WHEN SET_1.GAMES= 63
THEN 'GENERAL POOL ROUND OF 64 $'+CAST(CAST(SET_1.BracketBettingAmount AS INT) AS NVARCHAR)+''
WHEN SET_1.GAMES= 31
THEN 'GENERAL POOL ROUND OF 32 $'+CAST(CAST(SET_1.BracketBettingAmount AS INT) AS NVARCHAR)+''
WHEN SET_1.GAMES= 15
THEN 'GENERAL POOL SWEET 16 $'+CAST(CAST(SET_1.BracketBettingAmount AS INT) AS NVARCHAR)+''
ELSE ''
END) AS [PoolName],
(SELECT BracketNames FROM DBO.fnGetPoolWinner(SET_1.BracketBettingAmount,#TournamentId,
(CASE
WHEN SET_1.GAMES= 63
THEN 1
WHEN SET_1.GAMES= 31
THEN 2
WHEN SET_1.GAMES= 15
THEN 3
ELSE 0
END))) AS GroupEntries,
'Public' AS Access,
COUNT(SET_1.BracketId) AS Members,
COUNT(SET_1.BracketId)*SET_1.BracketBettingAmount AS CurrentPoolPrize,
(SELECT WinnerNames FROM DBO.fnGetPoolWinner(SET_1.BracketBettingAmount,#TournamentId,
(CASE
WHEN SET_1.GAMES= 63
THEN 1
WHEN SET_1.GAMES= 31
THEN 2
WHEN SET_1.GAMES= 15
THEN 3
ELSE 0
END))) AS WinnersName,
(CASE
WHEN SET_1.GAMES= 63
THEN 1
WHEN SET_1.GAMES= 31
THEN 2
WHEN SET_1.GAMES= 15
THEN 3
ELSE 0
END) AS RoundId,
SET_1.BracketBettingAmount AS BettingAmount
FROM
(SELECT BR.BracketId,
BracketBettingAmount,
(SELECT COUNT(1) FROM BracketPredictions AS BP WHERE BP.BracketPredictionBracketId =BR.BracketId) AS GAMES
FROM Brackets AS BR WHERE BR.BracketTournamentId = #TournamentId AND BR.IsDeleted = 0) SET_1 WHERE SET_1.GAMES > 0
GROUP BY SET_1.BracketBettingAmount, SET_1.GAMES HAVING SET_1.BracketBettingAmount IN (1,5,10,25)

try this, not tested
DECLARE #TournamentId INT = 1
with SET_1 as (
SELECT BR.BracketId, BracketBettingAmount as BettingAmount, W.GAMES, TN.TournamentName,
case W.GAMES
WHEN 63 THEN 1
WHEN 31 THEN 2
WHEN 15 THEN 3
ELSE 0 END as IDGAME,
CASE W.GAMES
WHEN 63 THEN 'GENERAL POOL ROUND OF 64 $'+CAST(CAST(BracketBettingAmount AS INT) AS NVARCHAR)
WHEN 31 THEN 'GENERAL POOL ROUND OF 32 $'+CAST(CAST(BracketBettingAmount AS INT) AS NVARCHAR)
WHEN 15 THEN 'GENERAL POOL SWEET 16 $' +CAST(CAST(BracketBettingAmount AS INT) AS NVARCHAR)
ELSE '' END AS PoolName,
TN.TournamentId
FROM Brackets AS BR
cross apply
(
SELECT COUNT(*) GAMES FROM BracketPredictions AS BP WHERE BP.BracketPredictionBracketId =BR.BracketId
) W
inner join Tournaments TN on BR.BracketTournamentId=TN.TournamentId
WHERE BR.IsDeleted = 0 and BracketBettingAmount IN (1,5,10,25) and W.GAMES>0 and TN.TournamentId = #TournamentId
),
NbBracketId as ( select NbBracketId, count(*) Nb from SET_1 group by NbBracketId)
SELECT
Y.CustomerIds AccountNumber, X.TournamentName, X.PoolName, Y.BracketNames AS GroupEntries, 'Public' AS Access,
Z.NB AS Members, Z.NB*X.BettingAmount AS CurrentPoolPrize, Y.WinnerNames, X.IDGAME AS RoundId, X.BettingAmount
FROM SET_1 X
outer apply DBO.fnGetPoolWinner(SET_1.BracketBettingAmount, SET_1.TournamentId, SET_1.IDGAME) as Y
inner join NbBracketId Z on X.BracketId=Z.BracketId

DBO.fnGetPoolWinner can be optmize itself.
try this approach,
DECLARE #TournamentId INT = 1
DECLARE #TournamentName AS NVARCHAR(MAX)
SELECT #TournamentName = TournamentName FROM Tournaments WHERE TournamentId = #TournamentId
select #TournamentName TournamentName,
CustomerIds AS [AccountNumber]
,(CASE
WHEN SET_1.GAMES= 63
THEN 'GENERAL POOL ROUND OF 64 $'+CAST(CAST(SET_1.BracketBettingAmount AS INT) AS NVARCHAR)+''
WHEN SET_1.GAMES= 31
THEN 'GENERAL POOL ROUND OF 32 $'+CAST(CAST(SET_1.BracketBettingAmount AS INT) AS NVARCHAR)+''
WHEN SET_1.GAMES= 15
THEN 'GENERAL POOL SWEET 16 $'+CAST(CAST(SET_1.BracketBettingAmount AS INT) AS NVARCHAR)+''
ELSE ''
END) AS [PoolName]
,ca.BracketNames as GroupEntries
'Public' AS Access,
COUNT(SET_1.BracketId) AS Members,
COUNT(SET_1.BracketId)*SET_1.BracketBettingAmount AS CurrentPoolPrize
,WinnerNames as WinnersName
, (CASE
WHEN SET_1.GAMES= 63
THEN 1
WHEN SET_1.GAMES= 31
THEN 2
WHEN SET_1.GAMES= 15
THEN 3
ELSE 0
END) AS RoundId,
SET_1.BracketBettingAmount AS BettingAmount
FROM
(SELECT BR.BracketId,
BracketBettingAmount,
(SELECT COUNT(1) FROM BracketPredictions AS BP WHERE BP.BracketPredictionBracketId =BR.BracketId) AS GAMES
FROM Brackets AS BR WHERE BR.BracketTournamentId = #TournamentId AND BR.IsDeleted = 0) SET_1
WHERE SET_1.GAMES > 0
GROUP BY SET_1.BracketBettingAmount, SET_1.GAMES
HAVING SET_1.BracketBettingAmount IN (1,5,10,25)
cross apply(SELECT CustomerIds,BracketNames,WinnerNames
FROM DBO.fnGetPoolWinner(SET_1.BracketBettingAmount,#TournamentId,
(CASE
WHEN SET_1.GAMES= 63
THEN 1
WHEN SET_1.GAMES= 31
THEN 2
WHEN SET_1.GAMES= 15
THEN 3
ELSE 0
END)) )ca

Related

Case Count not returning expected information

I have an automated check script for each morning where the user will be informed of the current number of jobs running as long as they don't fall into the category of "expected running jobs".
I would expected StatusID to be GREEN for IMPORT and AMBER for BATCH due to the current counts being 4 and 3 respectivley
My current code is
DECLARE #Datecreated DATETIME = GetDate())
DECLARE #JobInfo AS TABLE
(
JobType INT,
JobID NVARCHAR(30),
StatusID NVARCHAR(30),
Message NVARCHAR(500),
DateCreated DATETIME,
ITEMS INT
)
INSERT INTO #JobInfo (JobType,JobID,StatusID,Message, DateCreated,ITEMS)
SELECT
0 as Jobtype,
'BATCH' AS JobID,
CASE WHEN Count(CASE JobTypeID WHEN 1 THEN 0 WHEN 30 THEN 0 WHEN 234 THEN 0 ELSE 1 end) >0 THEN N'AMBER' ELSE N'GREEN' END,
'Jobs running longer than 1 hour (ITEMS)',
CAST( #DateCreated AS NVARCHAR(30)),
COUNT(CASE JobTypeID WHEN 1 THEN 0 WHEN 30 THEN 0 WHEN 234 THEN 0 ELSE 1 end)
FROM BATCH.dbo.JOB (NOLOCK) WHERE StatusID = 3
AND JobTypeID NOT IN (1,30,4005)
INSERT INTO #JobInfo (JobType,JobID,StatusID,Message, DateCreated,ITEMS)
SELECT
0 as Jobtype,
'IMPORT' AS JobID,
CASE WHEN Count(CASE JobTypeID WHEN 191 THEN 0 WHEN 124 THEN 0 WHEN 4005 THEN 0 ELSE 1 end) >0 THEN N'AMBER' ELSE N'GREEN' END,
'Jobs running longer than 1 hour (ITEMS)',
CAST( #DateCreated AS NVARCHAR(30)),
COUNT(CASE JobTypeID WHEN 191 THEN 0 WHEN 124 THEN 0 WHEN 4005 THEN 0 ELSE 1 end)
FROM IMPORT.dbo.JOB (NOLOCK) WHERE StatusID = 3
AND JobTypeID NOT IN (191,124,4005)
SELECT * FROM #JobInfo
However currently the StatusID is AMBER for both and the ITEMS are 2 and 4 respectively
SELECT * FROM BATCH.dbo.JOB (NOLOCK) WHERE StatusID = 3 --shows 4 rows, 30,1,1072,234
SELECT * FROM IMPORT.dbo.JOB (NOLOCK) WHERE StatusID = 3 --shows 3 rows, 4005,124,191
Could someone please help explain why this is the case?

How to re-write my CASE expression to avoid this specific error message?

I am using SQL Server 2014. I have the following T-SQL query running against a table (T1). An extract of table T1 is given below:
ID N1 N2 N3 N4 N5 N6
1 2 10 12 25 29 30
2 10 13 23 24 35 39
3 1 20 23 26 32 40
4 5 9 11 12 28 35
...
Expected output:
I want the output of my query to find if any of the values [N1] to [N6] of the current [ID] are present in any of the values at 2 [ID] levels above.
To simplify, the query needs to find out if the values ([N1] to [N6]) at [ID] = 4 exists in the values at [ID]-2; that is at [ID] = 2
ID N1 N2 N3 N4 N5 N6 N1_ID-2 N2_ID-2 N3_ID-2 N4_ID-2 N5_ID-2 N6_ID-2
1 2 10 12 25 29 30 0 0 0 0 0 0
2 10 13 23 24 35 39 0 0 0 0 0 0
3 1 20 23 26 30 40 0 0 0 0 1 0
4 5 9 11 13 28 35 0 0 0 1 0 1
...
My query currently stands as follows:
USE MyDatabase
SELECT *,
(CASE WHEN [N1] IN (SELECT [N1], [N2], [N3], [N4], [N5], [N6] FROM [T1] WHERE [ID] = [ID] -2) THEN 1 ELSE 0 END) AS [N1_ID-2],
(CASE WHEN [N2] IN (SELECT [N1], [N2], [N3], [N4], [N5], [N6] FROM [T1] WHERE [ID] = [ID] -2) THEN 1 ELSE 0 END) AS [N2_ID-2],
(CASE WHEN [N3] IN (SELECT [N1], [N2], [N3], [N4], [N5], [N6] FROM [T1] WHERE [ID] = [ID] -2) THEN 1 ELSE 0 END) AS [N3_ID-2],
(CASE WHEN [N4] IN (SELECT [N1], [N2], [N3], [N4], [N5], [N6] FROM [T1] WHERE [ID] = [ID] -2) THEN 1 ELSE 0 END) AS [N4_ID-2],
(CASE WHEN [N5] IN (SELECT [N1], [N2], [N3], [N4], [N5], [N6] FROM [T1] WHERE [ID] = [ID] -2) THEN 1 ELSE 0 END) AS [N5_ID-2],
(CASE WHEN [N6] IN (SELECT [N1], [N2], [N3], [N4], [N5], [N6] FROM [T1] WHERE [ID] = [ID] -2) THEN 1 ELSE 0 END) AS [N6_ID-2]
FROM [T1]
Running the above set of code is giving me the following error message:
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
How can I correct my code to avoid this error?
You can use a self join and IN like this:
select t.*,
(case when t.n1 in (tprev.n1, tprev.n2, tprev.n3, tprev.n4, tprev.n5, tprev.n6) then 1 else 0 end) n1_comp,
(case when t.n2 in (tprev.n1, tprev.n2, tprev.n3, tprev.n4, tprev.n5, tprev.n6) then 1 else 0 end) as n2_comp,
. . .
from t left join
t tprev
on tprev.id = t.id - 2
select
t1.*,
case when t1.N1 in (t1_old.N1, t1_old.N2, t1_old.N3, t1_old.N4, t1_old.N5, t1_old.N6) then 1 else 0 end as [N1_ID-2],
case when t1.N2 in (t1_old.N1, t1_old.N2, t1_old.N3, t1_old.N4, t1_old.N5, t1_old.N6) then 1 else 0 end as [N2_ID-2],
...
from
t1
left join t1 as t1_old on t1_old.id = t1.id - 2

how to show my data as in interval form in sql

I have a Table like that:
ID Class Marks
1 12th 0
2 10th 25
3 09th 24
4 12th 50
5 10th 60
6 09th 70
Desired Output Like that:-
Marks CLass12th class9th class10th
0-25 1 1 1
25-50 1 0 0
50-60 1 0 1
60-70 0 1 1
Total 3 2 3
how can i do same with sql
CREATE TABLE marks
(
id INT,
class VARCHAR(200),
marks INT
);
INSERT INTO marks
VALUES (1,
'12th',
0);
INSERT INTO marks
VALUES (1,
'10th',
25);
INSERT INTO marks
VALUES (1,
'9th',
24);
INSERT INTO marks
VALUES (1,
'12th',
50);
INSERT INTO marks
VALUES (1,
'10th',
60);
INSERT INTO marks
VALUES (1,
'9th',
70);
-----not able to put (0-24) condition in marks as it is actually minus the value as -24 -----
SELECT CASE
WHEN marks >= 0
AND marks < 25 THEN ( 024 )
WHEN marks >= 25
AND marks <= 50 THEN ( 2550 )
WHEN marks >= 51
AND marks < 60 THEN ( 5160 )
WHEN marks >= 60
AND marks < 71 THEN ( 6070 )
ELSE NULL
END AS marks,
Sum(class12th) AS CLass12th,
Sum(class10th) AS CLass9th,
Sum(class9th) AS CLass9th
FROM (SELECT id,
marks,
[12th] AS CLass12th,
[10th] AS CLass10th,
[9th] AS CLass9th
FROM (SELECT id,
class,
marks
FROM marks) AS SourceTable
PIVOT ( Count(class)
FOR class IN ([12th],
[10th],
[9th]) ) AS pivottable)a
GROUP BY marks
Try this :
select '0-25', sum(case when class = '12th' then 1 else 0 end) '12th',sum(case when class = '10th' then 1 else 0 end) '10th',sum(case when class = '9th' then 1 else 0 end) '9th'
from Yourtable where marks >= 0 and marks < = 25
union
select '25-50', sum(case when class = '12th' then 1 else 0 end),sum(case when class = '10th' then 1 else 0 end),sum(case when class = '9th' then 1 else 0 end)
from Yourtable where marks >= 25 and marks < = 50
union
select '50-60', sum(case when class = '12th' then 1 else 0 end),sum(case when class = '10th' then 1 else 0 end),sum(case when class = '9th' then 1 else 0 end)
from Yourtable where marks >= 50 and marks < = 60
union
select '60-70', sum(case when class = '12th' then 1 else 0 end),sum(case when class = '10th' then 1 else 0 end),sum(case when class = '9th' then 1 else 0 end)
from Yourtable where marks >= 60 and marks < = 70
union
select 'total', sum(case when class = '12th' then 1 else 0 end),sum(case when class = '10th' then 1 else 0 end),sum(case when class = '9th' then 1 else 0 end)
from Yourtable
You need to store your ranges our use a CTE and use it in a query like this:
;with ranges as (
select 0 fromMark, 25 toMark, '0-25' title
union all select 25,50, '25-50'
union all select 50,60, '50-60'
union all select 60,70, '60-70'
union all select 0,100, 'Total'
)
select
r.title,
count(case when t.Class = '12th' then 1 end) Class12th,
count(case when t.Class = '09th' then 1 end) Class9th,
count(case when t.Class = '10th' then 1 end) Class10th
from yourTable t
left join ranges r
on t.Marks >= r.fromMark and t.Marks < r.toMark
group by
r.title;

Using a loop in SQL to populate the table (SQL Server)

I am quite new with SQL and loops especially and need some help with the following problem.
I have a table like this:
SpotID EventID MaxTemp
123 1 45
236 1 109
69 1 18
123 2 216
236 2 29
69 2 84
123 3 91
236 3 457
69 3 280
I would like to generate a new table with the following output:
SpotID Over30 Over70 Over100
123 3 2 1
236 2 2 2
69 2 2 1
So what i am after is the count of how many times did the temperature exceed the limits of 30, 70 and 100 per SpotID for different EventIDs.
Is there a way to do this with a loop? My data set is obviously bigger and I am curious if how could i use something efficient.
Thank you very much.
Mike
You just need conditional aggregation:
select spotid,
sum(case when maxtemp > 30 then 1 else 0 end) as over_30,
sum(case when maxtemp > 70 then 1 else 0 end) as over_70
sum(case when maxtemp > 100 then 1 else 0 end) as over_100
from likethis
group by spotid;
If you just want to learn how to use loops....
DECLARE #DATA TABLE (
SpotID INT,
EventID INT,
MaxTemp INT
);
DECLARE #NEWDATA TABLE (
SpotID INT,
T30 INT,
T90 INT,
T100 INT
);
DECLARE
#SPOT AS INT,
#T30 AS INT,
#T90 AS INT,
#T100 AS INT;
INSERT INTO #DATA VALUES
(123, 1, 45 ),
(236, 1, 109),
(69 , 1, 18 ),
(123, 2, 216),
(236, 2, 29 ),
(69 , 2, 84 ),
(123, 3, 91 ),
(236, 3, 457),
(69 , 3, 280);
DECLARE STATION CURSOR FOR SELECT SpotID FROM #DATA GROUP BY SpotID;
OPEN STATION;
FETCH NEXT FROM STATION INTO #SPOT;
WHILE ##FETCH_STATUS = 0
BEGIN
SET #T30 = 0;
SET #T90 = 0;
SET #T100 = 0;
SELECT
#T30 = SUM(CASE WHEN MaxTemp > 30 AND MaxTemp < 70 THEN 1 ELSE 0 END),
#T90 = SUM(CASE WHEN MaxTemp >= 70 AND MaxTemp < 100 THEN 1 ELSE 0 END),
#T100 = SUM(CASE WHEN MaxTemp >= 100 THEN 1 ELSE 0 END)
FROM #DATA WHERE SpotID = #SPOT
INSERT INTO #NEWDATA VALUES (#SPOT,#T30,#T90,#T100)
FETCH NEXT FROM STATION INTO #SPOT;
END;
CLOSE STATION;
DEALLOCATE STATION;
SELECT * FROM #NEWDATA
Not anyway I would write the code requested, but this example shows how to create table variables, a simple cursor for looping, and writing to answers to variables that are loaded into a new table.
A lot of moving parts but it can give you insight to doing loops.
One minor change to the previous post, my version only counts within each temp range, else the lower temps will count most temps not temps in that range.
DECLARE #DATA TABLE (
SpotID INT,
EventID INT,
MaxTemp INT
)
INSERT INTO #DATA VALUES
(123, 1, 45 ),
(236, 1, 109),
(69 , 1, 18 ),
(123, 2, 216),
(236, 2, 29 ),
(69 , 2, 84 ),
(123, 3, 91 ),
(236, 3, 457),
(69 , 3, 280)
SELECT
SpotID,
SUM(CASE WHEN MaxTemp > 30 AND MaxTemp < 70 THEN 1 ELSE 0 END) AS OVER_30,
SUM(CASE WHEN MaxTemp >= 70 AND MaxTemp < 100 THEN 1 ELSE 0 END) AS OVER_70,
SUM(CASE WHEN MaxTemp >= 100 THEN 1 ELSE 0 END) AS OVER_100
FROM
#DATA
GROUP BY
SpotID

Sub select & union all

SELECT C.ClientCaseNumber,
Sum(CASE
WHEN CA.CaseActionDefinitionId IN (28, 29, 30) THEN 1
ELSE 0
END) AS [Wezwania],
Sum(CASE
WHEN CA.CaseActionDefinitionId IN (14, 21) THEN 1
ELSE 0
END) AS [Kontakt],
Sum(CASE
WHEN CA.CaseActionDefinitionId = 32 THEN 1
ELSE 0
END) AS [SMS],
Sum(CASE
WHEN CA.CaseActionDefinitionId = 44 THEN 1
ELSE 0
END) AS [Zgon],
Sum(CASE
WHEN CA.CaseActionDefinitionId = 49 THEN 1
ELSE 0
END) AS [Areszt],
Sum(CASE
WHEN CA.CaseActionDefinitionId = 37 THEN 1
ELSE 0
END) AS [Odmowa],
Sum(CASE
WHEN CA.CaseActionDefinitionId = 39 THEN 1
ELSE 0
END) AS [Podważa],
Sum(CASE
WHEN CA.CaseActionDefinitionId = 99 THEN 1
ELSE 0
END) AS [Ugoda],
[Adres],
[Numer],
[Mail],
[Powód]
FROM (SELECT Notes AS [Adres]
FROM CaseActionHistory
WHERE CaseActionDefinitionId = 68
UNION ALL
SELECT Info AS [Numer]
FROM CaseActionHistory
WHERE CaseActionDefinitionId IN (54, 55, 56, 58,
59, 60, 61, 62, 63)
UNION ALL
SELECT Notes AS [Mail]
FROM CaseActionHistory
WHERE CaseActionDefinitionId = 66
UNION ALL
SELECT Description AS [Powód]
FROM CaseActionDefinition
JOIN CaseActionHistory AS C
ON DefinitionId = C.CaseActionDefinitionId
WHERE DefinitionId BETWEEN 70 AND 78) AS x
INNER JOIN CaseDetails AS C
ON x.CaseDetailId = C.CaseDetaislId
INNER JOIN CaseActionHistory AS CA
ON C.CaseDetailsId = CA.CaseDetailId
WHERE C.ClientId = '11'
GROUP BY C.ClientCaseNumber
I've got such query. As return shows error of invalid columns "CaseDetailId, CaseDetailsId, Mail, Numer, Powód".
http://oi39.tinypic.com/2vwy44n.jpg
That's more or less how the results should look like.
ClientCaseNumber is taken from table CaseDetails
All the sums are sums of code added to CaseActionHistory table.
Notes/Info are in CaseActionHistory table
Description is placed in CaseActionDefinition table.
Between tables there are such connections:
CaseDetails.CaseDetailId = CaseActionHistory.CaseDetailsId
CaseActionHistory.CaseActionDefinitionId = CaseActionDefinition.DefinitionId
The UNION clause does not work like that.
This query:
select Notes as [Adres] from CaseActionHistory where ...
UNION ALL
select Info as [Numer] from CaseActionHistory where ...
UNION ALL
select Notes as [Mail] from CaseActionHistory where ...
UNION ALL
select Description as [Powód] from CaseActionDefinition join CaseActionHistory ...
will not populate a table with 4 columns. Instead it will be a table with one column, with all the values one after the other. The name of the column will be taken from the first SELECT, i.e.
if the first query returns values 1 and 2,
the second query returns values 3 and 4
the third query returns values 5 and 6
the fourth query returns values 7 and 8
you wont get:
Adres | Numer | Mail | Powód
------------------------------
1 | 3 | 5 | 7
2 | 4 | 6 | 8
but you'll get:
Adres
-------
1
2
3
4
5
6
7
8
Are you not missing the alias 'x' from these fields:
SELECT
C.ClientCaseNumber
,sum(case when CA.CaseActionDefinitionId in (28,29,30) then 1 else 0 end) as [Wezwania]
,sum(case when CA.CaseActionDefinitionId in (14,21) then 1 else 0 end) as [Kontakt]
,sum(case when CA.CaseActionDefinitionId = 32 then 1 else 0 end) as [SMS]
,sum(case when CA.CaseActionDefinitionId = 44 then 1 else 0 end) as [Zgon]
,sum(case when CA.CaseActionDefinitionId = 49 then 1 else 0 end) as [Areszt]
,sum(case when CA.CaseActionDefinitionId = 37 then 1 else 0 end) as [Odmowa]
,sum(case when CA.CaseActionDefinitionId = 39 then 1 else 0 end) as [Podważa]
,sum(case when CA.CaseActionDefinitionId = 99 then 1 else 0 end) as [Ugoda]
,x.[Adres]
,x.[Numer]
,x.[Mail]
,x.[Powód]
FROM
(select Notes as [Adres] from CaseActionHistory where CaseActionDefinitionId = 68
UNION ALL
select Info as [Numer] from CaseActionHistory where CaseActionDefinitionId in (54,55,56,58,59,60,61,62,63)
UNION ALL
select Notes as [Mail] from CaseActionHistory where CaseActionDefinitionId = 66
UNION ALL
select Description as [Powód] from CaseActionDefinition join CaseActionHistory as C on DefinitionId = C.CaseActionDefinitionId where DefinitionId between 70 and 78)
AS x
inner join CaseDetails as C on x.CaseDetailId = C.CaseDetaislId
inner join CaseActionHistory as CA on C.CaseDetailsId = CA.CaseDetailId
where C.ClientId = '11'
GROUP by C.ClientCaseNumber