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

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".

Related

Count (Select * Join) mysql query

I'm stuck on this for hours, I'm trying to COUNT how many subscribers are there in Group A, Group B, Group C for this particular query:
SELECT rh.id_subscriber, rh.bill_month, rh.bill_year,
(
SELECT tbl_gen_info.gen_data_03
FROM tbl_subscriber
LEFT JOIN tbl_gen_info ON tbl_subscriber.bill_area_code = tbl_gen_info.gen_data_01
WHERE rh.id_subscriber = tbl_subscriber.id_subscriber
) AS group_area
FROM tbl_reading_head AS rh
WHERE rh.id_soa_head IS NULL
AND rh.read_status <> 'Beginning'
AND rh.rec_status = 'active'
ORDER BY rh.id_subscriber
The sub-query gets the Group area gen_data_03 from tbl_gen_info
Tables contain this information:
tbl_gen_info
--------------------------------------------
| gen_category | gen_data_01 | gen_data_03 |
--------------------------------------------
| Area Code | Camacho St. | Group A |
--------------------------------------------
tbl_subscriber
----------------------------------
| id_subscriber | bill_area_code |
----------------------------------
| 1 | Camacho St. |
----------------------------------
tbl_reading_head
----------------------------------------------------------------------
| id_subscriber | id_soa_head | read_status | bill_month | bill_year |
----------------------------------------------------------------------
| 1 | NULL | Metered | 10 | 2017 |
----------------------------------------------------------------------
Notice that each id_subscriber has two (2) rows (one for electric, one for water). After grouping by id_subscriber:
GROUP BY rh.id_subscriber
I got this:
I tried adding COUNT before the sub-query making it:
COUNT(SELECT tbl_gen_info.gen_data_03 ...) AS group_area
but that doesn't work.
Use a subquery:
SELECT rh.group_area, COUNT(*)
FROM (SELECT rh.id_subscriber, rh.bill_month, rh.bill_year,
(SELECT tbl_gen_info.gen_data_03
FROM tbl_subscriber LEFT JOIN
tbl_gen_info
ON tbl_subscriber.bill_area_code = tbl_gen_info.gen_data_01
WHERE rh.id_subscriber = tbl_subscriber.id_subscriber
) as group_area
FROM tbl_reading_head rh
WHERE rh.id_soa_head IS NULL AND
rh.read_status <> 'Beginning' AND
rh.rec_status = 'active'
) rh
GROUP BY rh.group_area;

How can I join a table with itself with NULL values

I have this table (test):
+----+---------+-----+---+
| ID | Name | A | B |
+----+---------+-----+---+
| 1 | Steve | 200 | 0 |
| 2 | Steve | 200 | 1 |
| 5 | James | 90 | 0 |
| 4 | James | 50 | 1 |
| 3 | Warrick | 100 | 1 |
+----+---------+-----+---+
and this SQL query:
SELECT one.Name as Name, one.A as one_value, zero.A as zero_value
FROM test one LEFT JOIN test zero ON one.Name = zero.Name AND one.A <> zero.A
WHERE zero.B = 0 AND one.B = 1
which returns:
+-------+-----------+------------+
| Name | one_value | zero_value |
+-------+-----------+------------+
| James | 50 | 90 |
+-------+-----------+------------+
But what I want is when a record exists only with B = 1 that it is included in the response with a NULL value or something in the zero_value column, like this:
+---------+-----------+------------+
| Name | one_value | zero_value |
+---------+-----------+------------+
| James | 50 | 90 |
| Warrick | 100 | NULL |
+---------+-----------+------------+
How can I do this?
Edit:
I worked it out:
SELECT one.Name, one.A, zero.A
FROM test one LEFT JOIN test zero ON one.Name = zero.Name AND ( zero.B = 0 OR zero.B is NULL )
WHERE ( one.A <> zero.A OR zero.A is null )
Because of the left join the value of zero.B may be NULL, so you need to extend the WHERE condition:
WHERE one.B=1 AND (zero.B IS NULL OR zero.B = 0)
Update
You should also move the score condition down into WHERE:
WHERE one.B=1 AND (zero.B IS NULL OR zero.B = 0)
AND (zero.A IS NULL OR one.A <> zero.A)
How about this
select Name ,
(case when B= 0 Then A else null) as zero_value,
(case when B= 1 Then A else null) as one_value
from test
LEFT JOIN is a good thing here, this is what you want :
SELECT
one.Name
,one.A as one_value
, zero.A as zero_value
FROM test one
LEFT JOIN test zero
on one.Name = zero.Name
and zero.B = 0
where one.B = 1
Perhaps you want to handle when record exists only with B = 0 that it is included in the response with a NULL value in the one_value column in same time :
SELECT
test.Name
, one.A as one_value
, zero.A as zero_value
FROM
( SELECT Name
FROM test
GROUP BY Name) test
LEFT JOIN test one
on test.Name = one.Name
and one.B = 1
LEFT JOIN test zero
on test.Name = zero.Name
and zero.B = 0
Here is a demo for both queries :)
http://www.sqlfiddle.com/#!2/6332a/7/0
Try thiz query that give exact result for u
SELECT Test.nme,
one.A AS one_value,
zero.A AS zero_value
FROM(SELECT name AS nme FROM test WHERE name NOT in( SELECT one.Name FROM test one LEFT JOIN test zero ON (one.Name = zero.Name AND one.A=zero.A)
WHERE zero.B=0 AND one.B=1)GROUP BY name)Test
LEFT JOIN test one ON test.nme=one.Name AND one.B=1
LEFT JOIN test zero ON test.nme=zero.Name AND zero.B=0;

MySQL: How to query for a column and include information from related columns in the same table?

In MySQL, I have a table like this:
+-----------------------+
| Assets |
+-----------------------+
| Id | Name | RootId |
+----+---------+--------+
| 1 | Asset A | 1 |
+----+---------+--------+
| 2 | Asset B | 2 |
+----+---------+--------+
| 3 | Asset C | 3 |
+----+---------+--------+
| 4 | Asset D | 2 |
+----+---------+--------+
| 5 | Asset E | 3 |
+----+---------+--------+
| 6 | Asset F | 3 |
+----+---------+--------+
Not the greatest table structure, I know...but I'm stuck with it for now.
I am trying to write a single query that, given an Id value, will return a RootId and RootName ONLY if there are exactly two (2) rows with the same RootId. Otherwise those columns should be NULL.
So, using the table above, if given an Id of 4 the query should return:
+----------------------------------+
| Assets |
+----------------------------------+
| Id | Name | RootId | RootName |
+----+---------+--------+----------+
| 4 | Asset D | 2 | AssetB |
+----+---------+--------+----------+
But if given any other Id value, such as 5, it should return:
+----------------------------------+
| Assets |
+----------------------------------+
| Id | Name | RootId | RootName |
+----+---------+--------+----------+
| 5 | Asset E | null | null |
+----+---------+--------+----------+
Any help on this would be greatly appreciated. I think it will require a subquery with a COUNT and possibly a GROUP BY, but I'm really not sure how to articulate it...
Thanks in advance!
The following should implement this logic:
select id, name,
(case when cnt = 2 then rootid end) as rootid,
(case when cnt = 2 then ari.name end) as rootname
from assets a join
(select rootid, count(*) as cnt
from assets a
group by rootid
) ri
on a.rootid = ri.rootid left join
assets ari
on a.rootid = ari.id
where id = 4;
You can also do this as:
select a.id, a.name,
(case when a.cnt = 2 then a.rootid end) as rootid,
(case when a.cnt = 2 then ari.name end) as rootname
from (select a.*,
(select count(*) from assets a2 where a2.rootid = a.rootid) as cnt
from assets a
where id = 4
) a left join
assets ari
on a.rootid = ari.id;
Without the full aggregation, this will perform better.
Here is a SQL Fiddle illustrating them.
Something like this will return the specified resultset:
SELECT a.Id
, a.Name
, IF(q.cnt=2,q.RootId,NULL) AS RootId
, IF(q.cnt=2,q.RootName,NULL) AS RootName
FROM Assets a
JOIN ( SELECT COUNT(1) AS cnt
, r.RootId
, r.RootName
FROM Assets r
JOIN Assets s
ON s.RootId = r.RootId
WHERE r.Id = 4
GROUP BY r.RootId, r.RootName
) q
ON q.Id = a.Id
If its possible for RootId to be NULL, then you'd want to use a LEFT [OUTER] JOIN, and include a . If you want to consider a NULL value for RootId as matching another NULL value, then replace the equality comparator with the null-safe equality comparison operator, <=>
Adding those two tweaks gives a more robust solution:
SELECT a.Id
, a.Name
, IF(q.cnt=2,q.RootId,NULL) AS RootId
, IF(q.cnt=2,q.RootName,NULL) AS RootName
FROM Assets a
JOIN ( SELECT COUNT(1) AS cnt
, r.RootId
, r.RootName
FROM Assets r
LEFT -- lef outer join
JOIN Assets s
ON s.RootId <=> r.RootId -- nullsafe equality
WHERE r.Id = 4
GROUP BY r.RootId, r.RootName
) q
ON q.Id = a.Id

Left Join with Find in set

I have tables as follows :
TABLE A
+-----+---------------+-------------+
| ID | DNR_DETAIL_ID | DESCRIPTION |
+-----+---------------+-------------+
| 1 | 1 | DESC A |
+-----+---------------+-------------+
| 2 | 2 | DESC B |
+-----+---------------+-------------+
| 3 | 3 | DESC C |
+-----+---------------+-------------+
TABLE B
+--------+---------------+
| DNR_ID | DNR_DETAIL_ID |
+------------------------+
| 1 | 1,2 |
+--------+---------------+
| 2 | 3 |
+--------+---------------+
As you can see, DNR_DETAIL_ID columns are common in both tables. What I want to do, left joining both tables with field values ( null or not )
THE RESULT SHOULD BE (IF DNR_ID = 1) :
+-------------+---------+
| DESCRIPTION | CHECKED |
+-------------+---------+
| DESC A | 1 |
+-------------+---------+
| DESC B | 1 |
+-------------+---------+
| DESC C | 0 |
+-------------+---------+
try this:
SELECT TA.description AS DESCRIPTION, CASE WHEN TB.checked IS NOT NULL THEN 1 ELSE 0 END AS CHECKED
FROM
(
select distinct description from TableA
) TA left join
(
SELECT description, 'checked' FROM TableA where dnt_detail_id in (
select dnr_detail_id from TableB where dnr_id = 1
)
)TB ON TB.description = TA.description
Try this using FIND_IN_SET()
SELECT
A.Description,
CASE WHEN B.DNR_ID IS NOT NULL THEN 1 ELSE 0 END as Checked
FROM A
LEFT JOIN B
ON FIND_IN_SET(A.DNR_DETAIL_ID, B.DNR_DETAIL_ID)
AND B.DNR_ID=1
SQLFiddle demo
SELECT a.DESCRIPTION,
CASE WHEN b.DNR_ID IS NOT NULL THEN 0 ELSE 1 END as CHECKED
FROM table_a a
LEFT JOIN table_b b
ON FIND_IN_SET(a.DNR_DETAIL_ID, b.DNR_DETAIL_ID)
Demo on sqlfiddle
Thank you so much guys. I have tried all of your suggestions but none of them work. Interesting thing is that code works well in sqlfiddle ( same schema and values ) but not working in local environment! Here is the query that working in local.
/**
* DNR_DETAIL_DESC IS TABLE A
* DNR_LIST IS TABLE B
*/
SELECT A.DNR_DETAIL_DESC,
CASE WHEN B.DNR_ID IS NOT NULL THEN 1 ELSE 0 END AS CHECKED
FROM MD_DNR_DETAIL A
LEFT JOIN (SELECT * FROM DNR_LIST WHERE DNR_ID = 1) AS B
ON FIND_IN_SET(A.DNR_DETAILT_ID, B.DNR_DETAIL_ID)
You can write it many ways, but here is the best way:
SELECT
MD_DNR_DETAIL.DNR_DETAIL_DESC as DESCRIPTION,
CASE WHEN DNR_LIST.DNR_ID IS NOT NULL THEN 1 ELSE 0 END AS CHECKED
FROM MD_DNR_DETAIL
LEFT JOIN DNR_LIST
ON FIND_IN_SET(MD_DNR_DETAIL.DNR_DETAILT_ID, DNR_LIST.DNR_DETAIL_ID)

Optimize nested query to single query

I have a (MySQL) table containing dates of the last scan of hosts combined with a report ID:
+--------------+---------------------+--------+
| host | last_scan | report |
+--------------+---------------------+--------+
| 112.86.115.0 | 2012-01-03 01:39:30 | 4 |
| 112.86.115.1 | 2012-01-03 01:39:30 | 4 |
| 112.86.115.2 | 2012-01-03 02:03:40 | 4 |
| 112.86.115.2 | 2012-01-03 04:33:47 | 5 |
| 112.86.115.1 | 2012-01-03 04:20:23 | 5 |
| 112.86.115.6 | 2012-01-03 04:20:23 | 5 |
| 112.86.115.2 | 2012-01-05 04:29:46 | 8 |
| 112.86.115.6 | 2012-01-05 04:17:35 | 8 |
| 112.86.115.5 | 2012-01-05 04:29:48 | 8 |
| 112.86.115.4 | 2012-01-05 04:17:37 | 8 |
+--------------+---------------------+--------+
I want to select a list of all hosts with the date of the last scan and the corresponding report id. I have built the following nested query, but I am sure it can be done in a single query:
SELECT rh.host, rh.report, rh.last_scan
FROM report_hosts rh
WHERE rh.report = (
SELECT rh2.report
FROM report_hosts rh2
WHERE rh2.host = rh.host
ORDER BY rh2.last_scan DESC
LIMIT 1
)
GROUP BY rh.host
Is it possible to do this with a single, non-nested query?
No, but you can do a JOIN in your query
SELECT x.*
FROM report_hosts x
INNER JOIN (
SELECT host,MAX(last_scan) AS last_scan FROM report_hosts GROUP BY host
) y ON x.host=y.host AND x.last_scan=y.last_scan
Your query is doing a filesort, which is very inefficient. My solutions doesn't. It's very advisable to create an index on this table
ALTER TABLE `report_hosts` ADD INDEX ( `host` , `last_scan` ) ;
Else your query will do a filesort twice.
If you want to select from the report_hosts table only once then you could use a sort of 'RANK OVER PARTITION' method (available in Oracle but not, sadly, in MySQL). Something like this should work:
select h.host,h.last_scan as most_recent_scan,h.report
from
(
select rh.*,
case when #curHost != rh.host then #rank := 1 else #rank := #rank+1 end as rank,
case when #curHost != rh.host then #curHost := rh.host end
from report_hosts rh
cross join (select #rank := null,#curHost = null) t
order by host asc,last_scan desc
) h
where h.rank = 1;
Granted it is still nested but it does avoid the 'double select' problem. Not sure if it will be more efficient or not - kinda depends what indexes you have and volume of data.