Display results in SQL that meet the criteria - mysql

select only those top 10 hospitals that have both kinds of ICU and SICU beds, i.e. only hospitals that have at least 1 ICU bed and at least 1 SICU bed can be included in this part of the analysis. Here is what I have so far
select bu.business_name as 'Hospital Name'
,sum(be.license_beds) as Total_Licenses
,case when be.bed_id = 4 then 'ICU' end as "ICU"
,case when be.bed_id = 15 then 'SICU' end as "SICU"
from bed_fact be
join bed_type bt
on be.bed_id = bt.bed_id
join business bu
on be.ims_org_id = bu.ims_org_id
where be.bed_id = 4
or be.bed_id = 15
and be.license_beds IS NOT NULL
group
by bu.business_name
order
by Total_Licenses DESC
limit 10
;
I need to some how only count the hospital that has at least one of ICU or SICU value

You want conditional aggregation and a having clause:
select
bu.business_name as Hospital_Name,
sum(be.license_beds) as Total_Licenses,
sum(be.bed_id = 4) as ICU,
sum(be.bed_id = 15) as SICU
from bed_fact be
inner join bed_type bt on be.bed_id = bt.bed_id
inner join business bu on be.ims_org_id = bu.ims_org_id
where be.bed_id in (4, 15) and be.license_beds is not null
group by bu.business_name
having ICU > 0 and SICU > 0
order by Total_Licenses desc
limit 10
If you don't what the counts in the resultset, then move the aggregate functions to the having clause:
select
bu.business_name as Hospital_Name,
sum(be.license_beds) as Total_Licenses
from bed_fact be
inner join bed_type bt on be.bed_id = bt.bed_id
inner join business bu on be.ims_org_id = bu.ims_org_id
where be.bed_id in (4, 15) and be.license_beds is not null
group by bu.business_name
having sum(be.bed_id = 4) > 0 and sum(be.bed_id = 15) > 0
order by Total_Licenses desc
limit 10

Related

Sql query for records which has entry but not exit

I have a travellers table
travellers(id,full_name)
and another table of traveller_history
travellers_history(id,traveller_id,status)
The status in travellers_history is a number field
I want record of all the travellers which has record of status 11 in traveller_history records but doesn't have record of status 12 in traveller_history.How do I achieve this in sql ?
You can count the travellers that have more "11"s than "12":
select th.traveller_id
from traveller_history th
group by th.traveller_id
having sum( status = 11 ) > sum( status = 12 )
Join the tables, group by traveler and set the conditions in the having clause:
select t.id, t.full_name
from travellers t inner join travellers_history h
on h.traveller_id = t.id
group by t.id, t.full_name
having sum(h.status = 12) = 0 and sum(h.status = 11) > 0
or:
select t.id, t.full_name
from travellers t inner join travellers_history h
on h.traveller_id = t.id
where h.status in (11, 12)
group by t.id, t.full_name
having max(h.status) = 11

Using two different measures in a having statement

I am including the code I am trying to use. What I want is to get a count of encounter id's for each doctor. I want to capture patients who have had at least 2 visits or who have had one preventive visit. I don't know how to make this work using the having statement. thanks for any assistance.
SELECT e.doctorID, COUNT(DISTINCT e.encounterID) AS VisitCount
FROM enc e
JOIN users u ON e.patientID = u.uid
Left JOIN diagnosis d ON e.encounterID = d.encounterID
LEFT JOIN items it ON d.itemID = it.itemID
LEFT JOIN itemdetail id ON it.itemID = id.itemID
WHERE e.encType = 1 AND e.status = 'CHK' AND e.deleteFlag = 0 AND
e.date BETWEEN DATE_ADD((LAST_DAY(DATE_ADD(CURDATE(),INTERVAL -2 MONTH))), INTERVAL 1 DAY) AND LAST_DAY(DATE_ADD(CURDATE(),INTERVAL -1 MONTH))
AND FLOOR(DATEDIFF(NOW(),u.ptdob)/365.25) >= 18 AND e.doctorID = e.resourceID
GROUP BY e.doctorID, id.value
HAVING
COUNT(e.patientid)>=2 OR
id.value in ('Z00.00', 'Z00.01')
You dont need to include id.value in grp by clause. Try to give valid condition in having clause with id.value
select e.doctorID,
COUNT(distinct e.encounterID) as VisitCount from enc e join users u on e.patientID = u.uid
left join diagnosis d on e.encounterID = d.encounterID left join items it on
d.itemID = it.itemID left join itemdetail id on
it.itemID = id.itemID where e.encType = 1 and e.status ='CHK' and e.deleteFlag = 0 and
e.date between DATE_ADD((LAST_DAY(DATE_ADD(CURDATE(), INTERVAL - 2 MONTH))), INTERVAL 1 DAY)
and LAST_DAY(DATE_ADD(CURDATE(), INTERVAL - 1 MONTH))
and
FLOOR(DATEDIFF(NOW(), u.ptdob) / 365.25) >= 18
and e.doctorID = e.resourceID group by e.doctorID
having COUNT(e.patientid) >= 2
or sum(case when id.value in ('Z00.00','Z00.01') then 1
else 0 end)>=1

Incompatibility with Mysql 5.7(Expression #1 of ORDER BY clause is not in SELECT list)

When I execute the following query I receive an Exception:
Error Code: 3065 Expression #1 of ORDER BY clause is not in SELECT
list, references column 'webstore.level_depth' which is not in
SELECT list; this is incompatible with DISTINCT
My Query:
SELECT DISTINCT c.id_parent, c.id_category, cl.name, cl.description, cl.link_rewrite
FROM `pj_category_shop` cs, `pj_category` c
INNER JOIN `pj_category_lang` cl ON (c.`id_category` = cl.`id_category` AND cl.`id_lang` = 1 AND cl.id_shop = 2 )
WHERE (c.`active` = 1 OR c.`id_category` = 2)
AND cs.`id_category` = c.`id_category`
AND cs.`id_shop` = 2
AND c.`id_category` != 1
AND `level_depth` <= 2
AND c.id_category IN (
SELECT id_category
FROM `pj_category_group`
WHERE `id_group` IN (3)
)
ORDER BY `level_depth` ASC, cl.`name` ASC;
Why is this happening?
I have find the answer for my question.Actually mysql 5.7 contains 'ONLY_FULL_GROUP_BY' in sql mode.So we can't perform orderby in the element that is not in select list.we have to change it from
'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'
into
'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'
We can done this by executing the following queries
SET SESSION sql_mode = 'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'
SET GLOBAL sql_mode = 'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'
ORDER BY column should be column listed in the SELECT list
Add c.level_depth in your select list
Try:
SELECT DISTINCT c.id_parent, c.id_category, cl.name, cl.description, cl.link_rewrite, c.level_depth
FROM `pj_category_shop` cs, `pj_category` c
INNER JOIN `pj_category_lang` cl ON (c.`id_category` = cl.`id_category` AND cl.`id_lang` = 1 AND cl.id_shop = 2 )
WHERE (c.`active` = 1 OR c.`id_category` = 2)
AND cs.`id_category` = c.`id_category` AND cs.`id_shop` = 2
AND c.`id_category` != 1
AND `level_depth` <= 2
AND c.id_category IN (SELECT id_category FROM `pj_category_group` WHERE `id_group` IN (3))
ORDER BY c.`level_depth` ASC, cl.`name` ASC;
Sql Feature Order by is as the name suggests used to order the Selected Columns on the basis of the Column mentioned in the below Syntax :
Order by Column_Name ASC/DESC
So if you don't add the column using which you have decided to retrieve order set of data in the select clause you will get this error.
SELECT DISTINCT c.id_parent, c.id_category, cl.name, cl.description, cl.link_rewrite
FROM `pj_category_shop` cs, `pj_category` c
INNER JOIN `pj_category_lang` cl ON (c.`id_category` = cl.`id_category` AND cl.`id_lang` = 1 AND cl.id_shop = 2 )
WHERE (c.`active` = 1 OR c.`id_category` = 2)
ORDER BY c.`level_depth` ASC, cl.`name` ASC
AND cs.`id_category` = c.`id_category` AND cs.`id_shop` = 2
AND c.`id_category` != 1
AND `level_depth` <= 2
AND c.id_category IN (SELECT id_category FROM `pj_category_group` WHERE `id_group` IN (3));
To summarize, you need to have the ORDER BY in the context of the SELECT command, in which case, with the WHERE, FROM and INNER JOIN.
Linking together some threads here - i believe it has to do with mysql version (we were able to bypass by using 5.7) and/or strict mode: https://github.com/publiclab/plots2/pull/8145
Thanks!
There is a way to bypass it. It is not the best practice that you can do ( I think that it is even worse... but if you don't have any control over your SQL_MODE it should work):
SELECT DISTINCT d.id_parent, d.id_category, d.name, d.description, d.link_rewrite
FROM (select c.id_parent, c.id_category, cl.name, cl.description, cl.link_rewrite
FROM `pj_category_shop` cs, `pj_category` c
INNER JOIN `pj_category_lang` cl ON (c.`id_category` = cl.`id_category` AND cl.`id_lang` = 1 AND cl.id_shop = 2 )
WHERE (c.`active` = 1 OR c.`id_category` = 2)
ORDER BY c.`level_depth` ASC, cl.`name` ASC
AND cs.`id_category` = c.`id_category` AND cs.`id_shop` = 2
AND c.`id_category` != 1
AND `level_depth` <= 2
AND c.id_category IN (SELECT id_category FROM `pj_category_group` WHERE `id_group` IN (3))) as d ;

Select in Select MySQL

I have two queries, i'd like if is possible execute in only one query as a Select in Select.
The first one:
SELECT
users.id
FROM users
LEFT JOIN users_date ON users_date.user = users.id
LEFT JOIN users_varchar ON users_varchar.user = users.id
WHERE
abilitato = 1
AND users_date.key = 'birthday'
AND users_varchar.key = 'nation'
AND users_varchar.value = 'US'
AND (users.reg_date >= '2013-05-31' AND users.reg_date <= '2013-05-31')
AND (floor(DATEDIFF(NOW(), users_date.value) / 365) >= 19 AND floor(DATEDIFF(NOW(), users_date.value) / 365) <= 19)
it retrieve a list of user id (filtered by Age, Nation or Date of registration)
the second one:
SELECT count(`matches`.`id`) FROM `matches` WHERE (`matches`.`status_home` = 3 AND `matches`.`status_guest` = 3) AND (`matches`.`team_home` = 13 OR `matches`.`team_guest` = 13)
i need perform the second select for every ID retrieved by the one's.
for every perform i must replace the value 13 with the id retrieved.
it is possible perform all in a single query with a select in select?
thanks advance for your help
Try this sql.
SELECT count(`matches`.`id`)
FROM `matches` m
INNER JOIN ( SELECT users.id as id
FROM users
LEFT JOIN users_date ON users_date.user = users.id
LEFT JOIN users_varchar ON users_varchar.user = users.id
WHERE abilitato = 1
AND users_date.key = 'birthday'
AND users_varchar.key = 'nation'
AND users_varchar.value = 'US'
AND (users.reg_date >= '2013-05-31' AND users.reg_date <= '2013-05-31')
AND (floor(DATEDIFF(NOW(), users_date.value) / 365) >= 19 AND floor(DATEDIFF(NOW(), users_date.value) / 365) <= 19)) t
on t.id=m.team_guest
WHERE (`matches`.`status_home` = 3 AND `matches`.`status_guest` = 3)
AND (`matches`.`team_home` = 13 OR `matches`.`team_guest` = t.id)
GROUP BY t.id
You can express what you want to do as an explicit join. But the question asks for a select within a select. For that, you need a correlated subquery. Here is the final query:
select users.id,
(SELECT count(`matches`.`id`)
FROM `matches`
WHERE (`matches`.`status_home` = 3 AND `matches`.`status_guest` = 3) AND
(`matches`.`team_home` = user.id OR `matches`.`team_guest` = users.id)
) as cnt
FROM users LEFT JOIN
users_date
ON users_date.user = users.id LEFT JOIN
users_varchar
ON users_varchar.user = users.id
WHERE abilitato = 1 AND users_date.key = 'birthday' AND
users_varchar.key = 'nation' AND users_varchar.value = 'US' AND
(users.reg_date >= '2013-05-31' AND users.reg_date <= '2013-05-31') AND
(floor(DATEDIFF(NOW(), users_date.value) / 365) >= 19 AND
floor(DATEDIFF(NOW(), users_date.value) / 365) <= 19
)
(The formatting helps me understand the query better.)
Doing this without a correlated subquery is a bit challenging because of the or in the matching condition.

MySQL query sub query or grouping

Each modx_site_content record may have several records in modx_site_tmplvar_contentvalues.
I need to retrieve both modx_site_tmplvar_contentvalues.value where the tvv.tmplvarid = 3 AND the tvv.tmplvarid = 1. where tvv.tmplvarid is a future date, I need to return the tvv.value of tvv.tmplvarid 3 which is a comma separated list of tags.
This query does not return the values I need & I'm not sure how to get just what I want.
SELECT sc.id, sc.pagetitle, tvv.value, tvv.tmplvarid, tvv.id, tvv.value
FROM modx_site_content sc
left join modx_site_tmplvar_contentvalues tvv on tvv.contentid = sc.id
where published = '1'
and (tvv.tmplvarid = '3' and tvv.value >= curdate())
order by sc.id;
basically in the end I need to return only the list of tags (tvv.tmplvarid = 3) where the other associated record (tvv.tmplvarid = 1) is a date in the future.
Any thoughts, can this be done with grouping instead? I don't actually need anything from the modx_site_content table.
So you need to return the tags both rows in the modx_site_tmplvar_contentvalues table that has tmplvarid of 1 and 3 both related to the same modx_site_content, but only when the tmplvarid 3 row has a datetime field in the future?
I would do two separate joins to the modx_site_tmplvar_contentvalues tabe:
SELECT tOne.value, tThree.value
FROM modx_site_tmplvar_contentvalues tOne
INNER JOIN modx_site_content c ON tOne.contentid = c.id
INNER JOIN modx_site_tmplvar_contentvalues tThree ON tThree.contentid = c.id
WHERE c.published = 1
AND tOne.tmplvarid = 1
AND tThree.tmplvarid = 3 AND tThree.date > NOW()
SQL Fiddle: http://sqlfiddle.com/#!2/a4031/2
I figured it out. Amazing what you can do if you just read the docs ;)
select tv.contentid, tv.value as eventdate, sc.id, sc.pagetitle, tvv.value from
(
select * from modx_site_tmplvar_contentvalues cv
where cv.tmplvarid = 3
and cv.value >= curdate()
) as tv
left join modx_site_content sc on sc.id = tv.contentid
left join modx_site_tmplvar_contentvalues tvv on tvv.contentid = sc.id
where (tvv.tmplvarid = 1)
order by value asc