SQL count of intersections with total field - mysql

For example we have this ServiceRequests source table in database:
| Id | ClientDepartment | ServiceType | DateTimeServiced |
|----|------------------|-------------|------------------|
| 1 | Sales | Networking | 15.01.17 |
| 2 | Development | Networking | 14.02.17 |
| 3 | Development | Networking | 09.04.17 |
| 4 | Sales | Software | 11.03.17 |
| 5 | Sales | Hardware | 30.03.17 |
| 6 | Development | Hardware | 15.04.17 |
Need to make SQL select query and get result:
|Client\Service| Networking | Software | Hardware | Total |
|--------------|------------|----------|----------|-------|
| Sales | 1 | 1 | 1 | 3 |
| Development | 2 | 0 | 1 | 3 |
Where numbers are count of intersections between ServiceType and ClientDepartment (services per department).
Trying something like this gives very wrong result:
select ClientDepartment,
(select count(t1.ClientDepartment)
from ServiceRequests t1
where t1.ServiceType = 'Networking'
) as Networking,
(select count(t1.ClientDepartment)
from ServiceRequests t1
where t1.ServiceType = 'Software'
) as Software,
(select count(t1.ClientDepartment)
from ServiceRequests t1
where t1.ServiceType = 'Hardware'
) as Hardware,
(select count(t1.ClientDepartment)
from ServiceRequests t1
) as Total
from ServiceRequests
group by ClientDepartment
|Client\Service| Networking | Software | Hardware | Total |
|--------------|------------|----------|----------|-------|
| Sales | 3 | 1 | 2 | 6 |
| Development | 3 | 1 | 2 | 6 |
Hope for help, create example table code

You could use sum on CASE WHEN and group by
in this way you dn't need subselect for each count
select
ClientDepartment
, sum(case when ServiceType = 'Networking' then 1 else 0 end )as Networking
, sum(case when ServiceType = 'Software' then 1 else 0 end ) as Software
, sum(case when ServiceType = 'Hardware' then 1 else 0 end ) as Hardware
, sum(case when ServiceType = 'Networking' then 1 else 0 end ) +
sum(case when ServiceType = 'Software' then 1 else 0 end ) +
sum(case when ServiceType = 'Hardware' then 1 else 0 end ) as Total
from ServiceRequests
group by ClientDepartment
this should work for both the DB ..

We Can Achieve Desired result using Dynamic Sql
IF OBJECT_ID('Tempdb..#Temp') IS NOT NULL
DROP TABLE #Temp
;With cte( Id , ClientDepartment , ServiceType , DateTimeServiced )
AS
(
SELECT 1 , 'Sales' , 'Networking' , '15.01.17' Union all
SELECT 2 , 'Development' , 'Networking' , '14.02.17' Union all
SELECT 3 , 'Development' , 'Networking' , '09.04.17' Union all
SELECT 4 , 'Sales' , 'Software' , '11.03.17' Union all
SELECT 5 , 'Sales' , 'Hardware' , '30.03.17' Union all
SELECT 6 , 'Development' , 'Hardware' , '15.04.17'
)
SELECT ClientDepartment,
ServiceType,
COUNT(ServiceType)OVER(Partition by ClientDepartment,ServiceType Order by Id) AS Cnt INTO #Temp FROM cte --Sample data created here
DECLARE #Column1 nvarchar(max),
#Sql nvarchar(max),
#Column2 nvarchar(max)
SELECT #Column1=STUFF((SELECT DISTINCT ', '+ 'ISNULL('+ServiceType +',''0'') AS '+ServiceType FROM #Temp
FOR XML PATH ('')),1,1,'')
SELECT #Column2=STUFF((SELECT DISTINCT ', '+ +QUOTENAME(ServiceType) FROM #Temp
FOR XML PATH ('')),1,1,'')
SET #Sql='
SELECT *,'+REPLACE(#Column2,',','+')+' AS Total FROM
(
SELECT ClientDepartment AS ''Client\Service'','+#Column1 +' FROM
(
SELECT * FROm #Temp
)AS SRc
PIVOT
(
MAX(Cnt) FOR ServiceType IN ('+#Column2+')
)AS PVT
)DT
Order by 1 desc
'
PRINT #Sql
EXEC(#Sql)
OutPut
Client\Service Hardware Networking Software Total
---------------------------------------------------------
Sales 1 1 1 3
Development 1 2 0 3

Related

How to convert rows to columns?

I've the following query:
SELECT first_period, period, sum(num) trans_num
FROM (SELECT (DATEDIFF(created_at, '2022-12-10') DIV 6) period,
user_id,
count(1) num,
MIN(MIN(DATEDIFF(created_at, '2022-12-10') DIV 6)) OVER (PARTITION BY user_id) as first_period
FROM pos_transactions
WHERE DATE(created_at) >= '2022-12-10'
GROUP BY user_id, DATEDIFF(created_at, '2022-12-10') DIV 6
) u
GROUP BY first_period, period
ORDER BY first_period, period
It returns the following result:
But now I need to make it visualize like a Cohort diagram. So I need to restructure the same result as follows:
+--------------+------+------+------+------+
| first_period | 0 | 1 | 2 | 3 |
+--------------+------+------+------+------+
| 0 | 6230 | 2469 | 2846 | 1713 |
| 1 | | 2589 | 742 | 375 |
| 2 | | | 3034 | 397 |
| 3 | | | | 1207 |
+--------------+------+------+------+------+
Any idea how can I do that?
WITH YOUR_TABLE_DATA(FIRST_PERIOD,PERIOD,TRANS_NUM)AS
(
SELECT 0,0,6230 UNION ALL
SELECT 0,1,2469 UNION ALL
SELECT 0,2,2846 UNION ALL
SELECT 0,3,1713 UNION ALL
SELECT 1,1,2589 UNION ALL
SELECT 1,2,742 UNION ALL
SELECT 1,3,375 UNION ALL
SELECT 2,2,3034 UNION ALL
SELECT 2,3,397 UNION ALL
SELECT 3,3,1207
)
SELECT C.FIRST_PERIOD,
MAX(
CASE
WHEN C.PERIOD=0
THEN C.TRANS_NUM
ELSE 0
END)AS ZERO,
MAX(
CASE
WHEN C.PERIOD=1
THEN C.TRANS_NUM
ELSE 0
END)AS ONE,
MAX(
CASE
WHEN C.PERIOD=2
THEN C.TRANS_NUM
ELSE 0
END)AS TWO,
MAX(
CASE
WHEN C.PERIOD=3
THEN C.TRANS_NUM
ELSE 0
END)AS THREE
FROM YOUR_TABLE_DATA AS C
GROUP BY C.FIRST_PERIOD

MySQL row into number of columns and sum

Could somebody help with my SQL?
I have a table with records such as:
ID | Car_num | Service | Price
---+---------+---------+------
1 | 001 | shower | 10
2 | 002 | TV | 5
3 | 001 | TV | 5
How to write an SQL query to get the following output?
ID |Car_num | shower | TV
---+--------+--------+---
1 | 001 | 10 | 5
2 | 002 | 0 | 5
Use a pivot query:
SELECT MIN(ID) AS ID,
Car_num,
MAX(CASE WHEN Service = 'shower' THEN Price ELSE 0 END) AS shower,
MAX(CASE WHEN Service = 'TV' THEN Price ELSE 0 END) AS TV
FROM yourTable
GROUP BY Car_num
SELECT ROW_NUMBER() OVER(ORDER BY Car_num) Id,Car_num ,ISNULL([TV],0) [TV],ISNULL([shower],0) [shower]
FROM
(
SELECT Car_num , _Service , ISNULL(Price,0) Price
FROM #Table
)Data
PIVOT
(
MAX(Price) FOR _Service IN ([TV],[shower])
)AS PVT
Try this:
SELECT ID, Car_num
, SUM(IF(Service = 'shower', Price, 0)) AS Shower
, SUM(IF(Service = 'TV', Price, 0)) AS TV
FROM your_table
GROUP BY Car_num;

"Faking" a sub-table of results from 3 tables, in SQL

If I have a table of cases:
CASE_NUMBER | CASE_ID | STATUS | SUBJECT |
----------------------------------------------------------------
3108 | 123456 | Closed_Billable | Something Interesting
3109 | 325124 | Closed_Billable | Broken printer
3110 | 432432 | Open_Assigned | Email not working
And a table of calls:
PARENT_ID | STATUS | DUR(H) | DUR(M) | SUBJECT
---------------------------------------------------------------
123456 | Held | 1 | 30 | Initial discussion
123456 | Cancelled | 0 | 0 | Walk user through
123456 | Held | 0 | 45 | Remote debug session
325124 | Held | 1 | 0 | Consultation
325124 | Held | 1 | 15 | Needs assessment
432432 | Held | 1 | 30 | Support call
And a table of meetings:
PARENT_ID | STATUS | DUR(H) | DUR(M) | SUBJECT
-------------------------------------------------------
123456 | Held | 3 | 15 | On-site work
325124 | Held | 2 | 0 | Un-jam printer
432432 | Held | 1 | 0 | Reconnect network
How do I do a select with these parameters (this is not working code, obviously):
SELECT cases.case_number, cases.subject, calls.subject, meetings.subject
WHERE cases.status="Closed_Billable" AND (calls.status="Held" OR meetings.status="Held)
LEFT JOIN cases
ON cases.case_id = calls.parent_id
LEFT JOIN cases
ON cases.case_id = meetings.parent_id
and end up with a "faked" nested table like:
CASE_NUMBER | CASE SUBJECT | # CALLS | # MEETINGS | CALL SUBJECT | MEETING SUBJECT | DURATION (H) | DURATION (M) | TOTAL
-----------------------------------------------------------------------------------------------------------------------------------------
3108 | Something Interesting | 2 | 1 | | | | | 5.5H
| | | | Initial Discussion | | 1 | 30 |
| | | | Remote Debug Session | | 0 | 45 |
| | | | | On-site work | 3 | 15 |
3109 | Broken printer | 2 | 1 | | | | | 4.25H
| | | | Consultation | | 1 | 0 |
| | | | Needs assessment | | 1 | 15 |
| | | | | Un-jam printer | 2 | 0 |
I've tried joins and subqueries the best I can figure out, but I get repeated entries - for example, each Meeting in a Case will show say 3 times, once for each Call in that case.
I'm stumped! Obviously there's other fields I'm pulling here, and doing COUNTs of Calls and Meetings, and SUMs of their durations, but I'd be happy just to show a table/sub-table like this.
Is it even possible?
Thanks,
David.
Assembling a query result in the exact format you want is .. somewhat of a pain. It can be done, but presentation stuff like that is best left to the application.
That said, this will do what you want:
select case when case_id > floor(case_id) then ''
else case_number
end case_number,
coalesce(q1.c, '') calls,
coalesce(q2.c, '') meetings,
coalesce(calls.subject, '') `call subject`,
coalesce(meetings.subject, '') `meeting subject`,
case when calls.subject is not null then calls.dhour
when meetings.subject is not null then meetings.dhour
else ''
end dhour,
case when calls.subject is not null then calls.dmin
when meetings.subject is not null then meetings.dmin
else ''
end dhour,
coalesce(q3.total, '') total
from
(
select case_number, case_id
from cases where status = 'Closed_Billable'
union select case_number, concat(case_id, '.1')
from cases where status = 'Closed_Billable'
union select case_number, concat(case_id, '.2')
from cases where status = 'Closed_Billable'
) main
left join
(select parent_id, count(*) c
from calls
where status != 'Cancelled'
group by parent_id ) q1
on q1.parent_id = case_id
left join
(select parent_id, count(*) c
from meetings
group by parent_id) q2
on q2.parent_id = case_id
left join
(select parent_id, sum(dhour + m) total
from
(select parent_id, dhour, dmin / 60 m
from calls
where status != 'Cancelled'
union all
select parent_id, dhour, dmin / 60 m
from meetings
) qq
group by parent_id
) q3
on q3.parent_id = case_id
left join calls
on concat(calls.parent_id, '.1') = main.case_id
left join meetings
on concat(meetings.parent_id, '.2') = main.case_id
order by case_id asc
Note, i've renamed your duration fields because i dislike the parenthesis in them.
We have to mangle the case_id a little bit inside the query in order to be able to get you your blank rows / fields - those are what makes the query cumbersome
There's a demo here: http://sqlfiddle.com/#!9/d59d4/21
edited code to work with different schema in comment fiddle
select case when case_id > floor(case_id) then ''
else case_number
end case_number,
coalesce(q1.c, '') calls,
coalesce(q2.c, '') meetings,
coalesce(calls.name, '') `call subject`,
coalesce(meetings.name, '') `meeting subject`,
case when calls.name is not null then calls.duration_hours
when meetings.name is not null then meetings.duration_hours
else ''
end duration_hours,
case when calls.name is not null then calls.duration_minutes
when meetings.name is not null then meetings.duration_minutes
else ''
end duration_hours,
coalesce(q3.total, '') total
from
(
select case_number, id as case_id
from cases where status = 'Closed_Billable'
union select case_number, concat(id, '.1') as case_id
from cases where status = 'Closed_Billable'
union select case_number, concat(id, '.2') as case_id
from cases where status = 'Closed_Billable'
) main
left join
(select parent_id, count(*) c
from calls
where status != 'Cancelled'
group by parent_id ) q1
on q1.parent_id = case_id
left join
(select parent_id, count(*) c
from meetings
group by parent_id) q2
on q2.parent_id = case_id
left join
(select parent_id, sum(duration_hours + m) total
from
(select parent_id, duration_hours, duration_minutes / 60 m
from calls
where status != 'Cancelled'
union all
select parent_id, duration_hours, duration_minutes / 60 m
from meetings
) qq
group by parent_id
) q3
on q3.parent_id = case_id
left join calls
on concat(calls.parent_id, '.1') = main.case_id
left join meetings
on concat(meetings.parent_id, '.2') = main.case_id
order by case_id asc
You can't really get final results like that without some seriously ugly "wrapper" queries, of this sort:
SET #prevCaseNum := 'blahdyblahnowaythisshouldmatchanything';
SET #prevCaseSub := 'seeabovetonotmatchanything';
SELECT IF(#prevCaseNum = CASE_NUMBER, '', CASE_NUMBER) AS CASE_NUMBER
, IF(#prevCaseNum = CASE_NUMBER AND #prevCaseSubject = CASE_SUBJECT, '', CASE_SUBJECT) AS CASE_SUBJECT
, etc.....
, #prevCaseNum := CASE_NUMBER AS prevCaseNum
, #prevCaseSubject = CASE_SUBJECT AS prevCaseSub
, etc....
FROM ( [the real query] ORDER BY CASE_NUMBER, etc....) AS trq
;
And then wrap all that with another select to strip the prevCase fields.
And even this still won't give you the blanks you want on the "upper right".

Swapping rows to columns

I've read previous posts regarding pivot table and swapping rows to columns, but I couldn't find correct answer for my question. I have below table in MySQL:
+--------+--------+
| Userid | gname |
+--------+--------+
| 12 | AVBD |
| 12 | ASD |
| 12 | AVFD |
| 12 | Aew1 |
| 12 | AVBD32 |
| 12 | ASD23 |
| 12 | AVBDe |
| 12 | ASDer |
| 45 | AVBD |
| 45 | ASD444 |
| 45 | AVBD44 |
| 45 | ASD44 |
| 453 | AVBD22 |
| 453 | ASD1 |
+--------+--------+
I want to produce an ordered pivot table:
+--------+--------+--------+--------+--------+--------+--------+--------+--------+
| Userid | gname1 | gname2 | gname3 | gname4 | gname5 | gname6 | gname7 | gname8 |
+--------+--------+--------+--------+--------+--------+--------+--------+--------+
| 12 | AVBD | ASD | AVFD | Aew1 | AVBD32 | ASD23 | AVBDe | ASDer |
| 45 | AVBD | ASD444 | AVBD44 | ASD44 | | | | |
| 453 | AVBD22 | ASD1 | | | | | | |
+--------+--------+--------+--------+--------+--------+--------+--------+--------+
the name of gname is dynamic and has no limit.
Here is the data setup along with a SQLFiddle http://sqlfiddle.com/#!2/65fec
CREATE TABLE gnames
(`Userid` int, `gname` varchar(6))
;
INSERT INTO gnames
(`Userid`, `gname`)
VALUES
(12, 'AVBD'),
(12, 'ASD'),
(12, 'AVFD'),
(12, 'Aew1'),
(12, 'AVBD32'),
(12, 'ASD23'),
(12, 'AVBDe'),
(12, 'ASDer'),
(45, 'AVBD'),
(45, 'ASD444'),
(45, 'AVBD44'),
(45, 'ASD44'),
(453, 'AVBD22'),
(453, 'ASD1')
;
This would be significantly easier if MySQL supported windowing functions because it's not necessarily the easiest to create a row number for each userid. I'll show you two ways to do this with hard-coded queries (limited number of results) and then I'll include one version that is using dynamic SQL.
In order to get the final result, you need some sequential number for each gname within the userid. This can be done a few different ways.
First, you can use a correlated subquery to count the number of gnames per user, you'd then use this sequence to create your new columns via an aggregate function with CASE expression:
select
userid,
max(case when gnameNum = 1 then gname else '' end) gname1,
max(case when gnameNum = 2 then gname else '' end) gname2,
max(case when gnameNum = 3 then gname else '' end) gname3,
max(case when gnameNum = 4 then gname else '' end) gname4,
max(case when gnameNum = 5 then gname else '' end) gname5,
max(case when gnameNum = 6 then gname else '' end) gname6,
max(case when gnameNum = 7 then gname else '' end) gname7,
max(case when gnameNum = 8 then gname else '' end) gname8
from
(
select userid,
gname,
(select count(*)
from gnames d
where g.userid = d.userid
and g.gname <= d.gname) as gnameNum
from gnames g
) src
group by userid;
See SQL Fiddle with Demo. Inside the subquery you are creating a row number for each gname, you then use this new value in the column creation. The problem with correlated subqueries is you could suffer from performance issues on larger data sets.
A second method would be to include user variables to create the row number. This code uses 2 variables to compare the previous row to the current row and increases the row number, if the userid is the same as the previous row. Again, you'd use the row number created to convert the data to new columns:
select
userid,
max(case when rownum = 1 then gname else '' end) gname1,
max(case when rownum = 2 then gname else '' end) gname2,
max(case when rownum = 3 then gname else '' end) gname3,
max(case when rownum = 4 then gname else '' end) gname4,
max(case when rownum = 5 then gname else '' end) gname5,
max(case when rownum = 6 then gname else '' end) gname6,
max(case when rownum = 7 then gname else '' end) gname7,
max(case when rownum = 8 then gname else '' end) gname8
from
(
select
g.userid,
g.gname,
#row:=case when #prev=userid then #row else 0 end + 1 as rownum,
#prev:=userid
from gnames g
cross join
(
select #row:=0, #prev:=null
) r
order by userid, gname
) src
group by userid;
See SQL Fiddle with Demo.
Now, in order to do this dynamically you will need to use a prepared statement. This process will create a sql string that you'll execute to get the final result. For this example, I used the user variable query above:
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'max(case when rownum = ',
rownum,
' then gname else '''' end) AS `gname',
rownum, '`'
)
) INTO #sql
from
(
select
g.userid,
g.gname,
#row:=case when #prev=userid then #row else 0 end + 1 as rownum,
#prev:=userid
from gnames g
cross join
(
select #row:=0, #prev:=null
) r
order by userid, gname
) src;
SET #sql = CONCAT('SELECT userid, ', #sql, '
from
(
select
g.userid,
g.gname,
#row:=case when #prev=userid then #row else 0 end + 1 as rownum,
#prev:=userid
from gnames g
cross join
(
select #row:=0, #prev:=null
) r
order by userid, gname
) src
group by userid');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
See SQL Fiddle with Demo. All three versions will give a result of:
| USERID | GNAME1 | GNAME2 | GNAME3 | GNAME4 | GNAME5 | GNAME6 | GNAME7 | GNAME8 |
|--------|--------|--------|--------|--------|--------|--------|--------|--------|
| 12 | Aew1 | ASD | ASD23 | ASDer | AVBD | AVBD32 | AVBDe | AVFD |
| 45 | ASD44 | ASD444 | AVBD | AVBD44 | | | | |
| 453 | ASD1 | AVBD22 | | | | | | |
One thing to consider when using the dynamic SQL is MySQL has a set length for the group_concat_max_len, if you have a lot of columns being created you might run into issues. You'll want to account for that. Here is another question that deals with this MySQL and GROUP_CONCAT() maximum length.

MySQL calculate score by rank in percentage

I am using MYSQL to create a rating system to implement my database. What I want to do is to rate each attribute by its percentage with some calculation. Here is the example database:
| ID | VALUE1 | VALUE2|
-----------------------
| 2 | 5 | 20 |
| 4 | 5 | 30 |
| 1 | 3 | 5 |
| 3 | 2 | 8 |
Here is the ideal output I need:
| ID | VALUE1 | RANK1 | Score1 | VALUE2 | RANK2 | Score2 |
---------------------------------------------------------
| 2 | 5 | 1 | 10 | 20 | 2| 8.3|
| 4 | 5 | 1 | 10 | 30 | 1| 10|
| 1 | 3 | 2 | 7.5| 5 | 4| 5|
| 3 | 2 | 3 | 5 | 8 | 3| 6.6|
The formula for score calculation is
5+5*(MaxRank-rank)/(MaxRank-MinRank)
How to generate multiple ranking like the table? I have tried
SELECT
#min_rank := 1 AS min_rank
, #max_rank1 := (SELECT COUNT(DISTINCT value1) FROM table) AS max_rank1
, #max_rank2 := (SELECT COUNT(DISTINCT value2) FROM table) AS max_rank2
;
SELECT
ID
, R1
, TRUNCATE(5.0+5.0 * (#max_rank1 - R1) / (#max_rank1 - #min_rank), 2) AS Score1
, R2
, TRUNCATE(5.0+5.0 * (#max_rank2 - R2) / (#max_rank2 - #min_rank), 2) AS Score2
FROM (
SELECT
ID
, value1
, FIND_IN_SET( `value1`, (SELECT GROUP_CONCAT(DISTINCT `value1` ORDER BY `value1` DESC) FROM table)) AS R1
, value2
, FIND_IN_SET( `value2`, (SELECT GROUP_CONCAT(DISTINCT `value2` ORDER BY `value2` DESC) FROM table)) AS R2
FROM table
) ranked_table;
It works fine with ranking below 170. My database has approximate 200+ ranking for some values and ranks larger then 170 will be seen as 0 when it returns. In that case, the scores with ranks >170 will be miscalculated. Thank you guys.
That looks nasty to calculate.
Something like this might do it
SELECT a.ID, a.VALUE1, Sub1.Rank1, (5.0+5.0 * (Sub3.MaxRank1 - Sub1.Rank1) / (Sub3.MaxRank1 - 1)) AS Score1, a.VALUE2, Sub2.Rank2, (5.0+5.0 * (Sub4.MaxRank2 - Sub2.Rank2) / (Sub4.MaxRank2 - 1)) AS Score2
FROM TestTable a
INNER JOIN (SELECT DISTINCT z.VALUE1, (SELECT ((COUNT(DISTINCT VALUE1) + 1)) FROM TestTable y WHERE z.VALUE1 < y.VALUE1) AS RANK1
FROM TestTable z
) Sub1 ON a.VALUE1 = Sub1.VALUE1
INNER JOIN (SELECT DISTINCT z.VALUE2, (SELECT ((COUNT(DISTINCT VALUE2) + 1)) FROM TestTable y WHERE z.VALUE2 < y.VALUE2) AS RANK2
FROM TestTable z
) Sub2 ON a.VALUE2 = Sub2.VALUE2
CROSS JOIN (SELECT COUNT(*) + 1 AS MaxRank1 FROM TestTable CROSS JOIN (SELECT MAX(VALUE1) AS MaxValue1 FROM TestTable) Sub3a WHERE VALUE1 < MaxValue1) Sub3
CROSS JOIN (SELECT COUNT(*) + 1 AS MaxRank2 FROM TestTable CROSS JOIN (SELECT MAX(VALUE2) AS MaxValue2 FROM TestTable) Sub4a WHERE VALUE2 < MaxValue2) Sub4
Note I am not sure on your score calculation. The equation you give doesn't appear to me to give the results in your example. But I might just be misreading it.