I have been trying to do this for over 2 hours but simply cannot figure it out.
I have 2 tables - 'patient' with 'PatientNum' column, and 'insurance_cover' with 'insuranceCode', 'patientNum' columns.
I want to show all patients with insurance, with their patient number and the amount of different insurance companies they are covered by(this is the part I've been having trouble with).
This is what I want the output to look like as the explaination may be confusing
Insurance Cover | Patient Number | Number of insurances
-------------------------------------------------------
With Insurance| 1 | 3
With Insurance| 2 | 1
With Insurance| 3 | 1
No Insurance | 4 | N/A
No Insurance | 5 | N/A
Also I realise I need to use UNION, but I haven't been able to get the first part working yet so haven't attempted that yet
Here is my current attempt
SELECT CONCAT('With Insurance ', pat.`PatientNum`)
AS `Insurance cover + Patient Number`,
CONCAT(pat.`PatientFirstname`, ' ', pat.`PatientSurname`)
AS `Patient Name`,
COUNT(`patientNum`) GROUP BY `patientNum`
FROM `patient` AS pat,
`insurance_cover` AS ins
WHERE ins.`PatientNum` = pat.`PatientNum`
AND ins.PatientNum IN (SELECT ins.`PatientNum`
FROM `insurance_cover`)
GROUP BY pat.`PatientNum`;
Any help is appreciated
Table definitions as requested are at http://imgur.com/a/7k22r (I cannot insert pictures with low rep)
You should use a query like:
SELECT patientNum,
number_of_insurances,
(CASE number_of_insurances WHEN 0 THEN 'Not covered' ELSE 'Covered' END)
FROM (
SELECT patient.patientNum,
count(*) as number_of_insurances,
FROM patient
LEFT JOIN insurance_cover ON patient.patientNum = insurance_cover.patientNum
GROUP BY patient.patientNum
) AS S
Edit: According to comments below, you cannot use JOIN. So here is another (less efficient) answer:
SELECT (CASE (SELECT COUNT(*)
FROM insurance_cover AS i1
WHERE i1.patientNum = p.patientNum
)
WHEN 0 THEN 'Not covered'
ELSE 'Covered'
END) AS covered,
p.patientNum,
(SELECT COUNT(*)
FROM insurance_cover AS i2
WHERE i2.patientNum = p.patientNum
) AS number_of_insurances
FROM patient p
Related
This is where I have reached after trying my best
select 13c_name,13c_mobile,13c_pid,p.13c_usid,p.13c_comp_id,13c_amount,
13c_mode,13c_month,13c_year,13c_rec,13c_rec_date,13c_check,13c_comments,
13c_status,13c_ip,13c_message,13c_rec_by,13c_invoice_pay from
13c_users u , 13c_payments p
where ( (u.13c_usid=p.13c_usid and 13c_subs='1') and (13c_year IN ('$new_year') and 13c_month NOT IN (1|2|3|4) or 13) )
What I want to achieve is something like this
I want to select all the members from 13c_users who have subscribed
(13c_subs='1') to monthly payments from table 13c_payments who may not
have paid any of the month of any year till now (13c_month stores the
month number and 13c_year stores the year number in 13c_payment table)
Now above query works some what nice but it does not select the users who have not paid anything yet, like of the user is subscribed and have not paid for any month the query will not match the join tbale with him.
Please check the query what I am doing wrong here!
////////////////////////////////// EDITED ///////////////////
This is until so far I could reach still I am not getting expected results:
select * from ( (select * from 13c_users u Left JOIN 13c_payments p ON
u.13c_usid=p.13c_usid where (13c_subs='1' and u.13c_comp_id='$yid') ) as T )
where ( (13c_year is NULL or 13c_year IN (2019) ) and (13c_month IS NULL or
13c_month NOT IN (1,2,3,4,5,6,7,8,9,10,11,12)) and (T.13c_invoice_pay='0' or T.13c_invoice_pay is
NULL ))
The above query, selects all the members who have never paid but not those members who have paid for the first 2 months and not after that.
Table payment gets the entry of every payment made in separate rows.
I know there is something wrong in this part of query for sure
(13c_year is NULL or 13c_year IN (2019) ) and (13c_month IS NULL or
13c_month NOT IN (1,2,3,4,5,6,7,8,9,10,11,12)
I want to select the row if the row does not have any of the month as mentioned there 13c_month NOT IN (1,2,3,4,5,6,7,8,9,10,11,12) but the rows are separate so it will always select every row
User table
Payments Table
Here's a much simplified example where I work out the number of expected payments and the number of months in which payment has been made - if not the same then I am interested
drop table if exists u,t;
create table u (id int,subs int, dt date);
create table t (uid int,dt date);
insert into u values (1,1,'2019-01-01'),(2,1,'2018-11-01'),(3,1,'2018-09-01');
insert into t values
(1,'2019-01-01'),
(2,'2018-11-11'),(2,'2018-11-13'),(2,'2019-01-01');
select id,
((year(now()) * 12 + month(Now())) - (year(u.dt) * 12 + month(u.dt))) + 1 numexpected,
coalesce(s.paidup,0) paidup
from u
left join
(select t.uid,count(distinct year(t.dt),month(t.dt)) paidup
from t
group by t.uid) s on s.uid = u.id
where ((year(now()) * 12 + month(Now())) - (year(u.dt) * 12 + month(u.dt))) + 1 <> coalesce(s.paidup,0);
+------+-------------+--------+
| id | numexpected | paidup |
+------+-------------+--------+
| 2 | 3 | 2 |
| 3 | 5 | 0 |
+------+-------------+--------+
2 rows in set (0.00 sec)
Note the expectation that a payment should be made every month seems a bit simplistic - what about pre-payments and late payments? For example UID 2 has made 3 payments but 2 were in the same month.
There is an error in my query and I would like some help. I have three tables
Rooms{id,number,name,type(ECO/LUX),active(0/1)}
Men{passport,roomid,status(YOUTH/ADULT)}
Women{passport,roomid,status(YOUTH/ADULT)}
**In each room there can be more than one woman or man.
I want to count how many women and men have the same room with roomid in (1,2,3), status='ADULT', type='LUX' and active=1. Therefore I need a result like this:
+----+--------+-----------+----------+------------+
| id | number | name | CountMen | CountWomen |
+----+--------+-----------+----------+------------+
| 1 | 23 | 1st suite | 2 | 4 |
| 3 | 4 | 2nd suite | 1 | 2 |
+----+--------+-----------+----------+------------+
SELECT id,number,name,
sum(case when Men.status='ADULT' then 1 else 0 end) as CountMen,
sum(case when Women.status='ADULT' then 1 else 0 end) as CountWomen
FROM Rooms left join Men
on Rooms.id=Men.roomid
left join Women on Room.id=Women.roomid where
(type='LUX') and (active=true) and (id in (1,2,3))
group by id;
The problem is that I get sometimes wrong results in the counters.
In a left join, conditions on the second table need to be in the on clause. It would help if you qualified all column names in the query.
However your problem is because you are getting a Cartesian product between the gender tables. This is definitely a case where gender segregation is not a good thing. You should have just one table for people (and this doesn't even bring up other issues with defining binary genders).
SELECT r.id, r.number, r.name,
(SELECT COUNT(*)
FROM men m
WHERE m.status = 'ADULT' AND r.id = m.roomid
) as CountMen,
(SELECT COUNT(*)
FROM women w
WHERE w.status = 'ADULT' AND r.id = w.roomid
) as CountWomen
FROM Rooms r
WHERE r.type = 'LUX' AND r.active = true AND r.id IN (1, 2, 3);
However, you should fix your data model so you have people rather than segregated gender tables.
Once again i need yours help ;). I have a lot data and mysql request are slower and slower so the need request that i need i want group in one comand.
My example DB structure:
|product|opinion (pos/neg)|reason|
__________________________________
|milk | pos | good |
|milk | pos |fresh |
|chocolate| neg | old |
|milk | neg | from cow|
So i need information about all diffrent product (GROUP BY) count of it, and count of pos opinion for each product. I want output like that:
|product|count|pos count|
_________________________
|milk | 3 | 2 |
|chocolate| 1 | 0 |
I hope that my explain was good enought ;)
Or go to work: I write two commands
SELECT COUNT(*) as pos count FROM table WHERE product = "milk" AND opinion = "pos" GROUP BY `opinion`
And Second one
SELECT product, COUNT(*) FROM table GROUP BY `product`
I don't know how to join this two request, maybe that is impossible? In my real use code i have additional category collumn and i use WHERE in second command too
select product,
count(*) as total_count
sum(
case when opinion='pos' then 1
else 0 end
) as pos_count
from the_table
group by product;
SELECT product,
COUNT(*) TotalCount,
SUM(opinion = 'pos') POSCount
FROM tableName
GROUP BY product
SUM(opinion = 'pos') is MySQL specific syntax that counts the total of result based from the result of boolean arithmethic. If you want it to be more RDBMS friends, use CASE
SUM(CASE WHEN opinion = 'pos' THEN 1 ELSE 0 END)
SQLFiddle Demo
I hope someone can lend an assist and some advise here. I'm trying to get a fairly complex result and not sure if I can do it as one query with subqueries, a union, or simply separate queries to be merged into excel after the fact.
I'm working with a legacy database from my predecessor with the following tables:
Business (columns working with: id, sector, state)
Forms (columns working with: Submitted (Y/N), id, business_id)
Inventory (Columns working with: In_stock (Y/N), id, form_id)
I'm trying to get a final result that looks like this:
| SubmittedForms | Unsubmitted Forms | Sector | State |
|-----------------------------------------------------|
| 10 | 5 | Agr | UT |
| 0 | 7 | Chem | MT |
| 2 | 1 | Bio | OK |
| 13 | 0 | Chem | NM |
The main problem I'm getting is that while submitted forms doesn't need any further arguments and is a simple count, the unsubmitted forms are dependent on the Inventory.in_stock='Y'. Here's my query for the submitted forms:
SELECT COUNT(Forms.id) AS Submitted, Business.sector, Business.state
FROM Forms
JOIN Business ON Forms.business_id=Business.id
WHERE Forms.submitted='Y'
GROUP BY Business.state, Business.sector
Unfortunately, I can't seem to get the unsubmitted forms number to calculate correctly. It just returns the total count of rows where in_stock is Y for that sector.
If it's easier to run a separate query for Submitted and Unsubmitted that's fine for the end result but I need some help getting the correct count of Unsubmitted forms with the in_stock flagged as Y. Also, I attempted to use a COUNT DISTINCT but takes way too long, was still running after 10 minutes. Another complication I can envision in a single query option is the possibility of 0/null values in either Submitted or Unsubmitted forms
Any help is greatly appreciated!
One option:
SELECT COUNT(CASE WHEN Forms.submitted = 'Y' THEN 1 END) SubmittedForms,
COUNT
( CASE WHEN Forms.submitted = 'N'
AND EXISTS ( SELECT 1
FROM Inventory
WHERE form_id = Forms.id
AND in_stock = 'Y'
)
THEN 1
END
) UnsubmittedForms,
Business.sector Sector,
Business.state State
FROM Forms
RIGHT
OUTER
JOIN Business
ON Forms.business_id = Business.id
GROUP
BY Business.sector,
Business.state
;
Another option, which might perform better:
SELECT COUNT(CASE WHEN Forms.submitted = 'Y' THEN 1 END) SubmittedForms,
COUNT(CASE WHEN Forms.submitted = 'N' THEN 1 END) UnsubmittedForms,
Business.sector Sector,
Business.state State
FROM ( SELECT *
FROM Forms
WHERE submitted = 'Y'
OR id IN ( SELECT DISTINCT form_id
FROM Inventory
AND in_stock = 'Y'
)
) Forms
RIGHT
OUTER
JOIN Business
ON Forms.business_id = Business.id
GROUP
BY Business.sector,
Business.state
;
ok this is very simple yet have been searching for 3 hours and still cant get it to work!
the scenario is i have a db with individual costs of 2 business' and i want to sum the cost of each business and present on screen. now i know this is simple enough and easily done with two SELECTS. but i want to do this in one query!
DB
|cost|business|
|100 | 1 |
|200 | 2 |
|200 | 1 |
|300 | 2 |
so from the table above we know that b1 = 300 and b2 = 500! but none of my queries work!
i have tried UNION and CASE but am unfamiliar with them.
my queries:
first try:
$buscost = mysql_query("SELECT FORMAT(sum(`cost`),2) as `b1` FROM `outgoing` WHERE `business`=1
UNION
SELECT FORMAT(sum(`cost`),2) as `b2` FROM `outgoing` WHERE `business`=2")
or die(mysql_error());
$buscost = mysql_fetch_array($busowe);
second try:
$buscost = mysql_query("SELECT
CASE WHEN `business` = 1 THEN FORMAT(sum(`cost`),2) END AS `b1` ,
CASE WHEN `business` = 2 THEN FORMAT(sum(`cost`),2) END AS `b2`
FROM `outgoing` WHERE `active`='yes' ");
$buscost = mysql_fetch_array($buscost);
*cost is set as float(11,2).
im sure im close i just dont know enough to figure it out, have found similar questions on here but none of the answers helped!
oh and if i print_r, the first only fetches the sum of b1, b2 doesnt exist! and
the second array all i get is the result set of the first case and case 2 "b2" is empty,but exists!! i have checked the tables and there is test data in there for both business'.
please help any advice or a solution is greatly appreciated.
edit:forgot to mention all results will also need to be filtered with where active='yes'
Youn need to group by:
SELECT business, FORMAT(sum(`cost`),2) AS cost
FROM outgoing
WHERE active = 'yes'
GROUP BY business
if you want the format:
business | cost
b1 | 300
b2 | 500
or
SELECT
(
SELECT FORMAT(sum(`cost`),2) as `b1`
FROM `outgoing`
WHERE `business`=1 AND active = 'yes'
GROUP BY business
) AS b1,
(
SELECT FORMAT(sum(`cost`),2) as `b1`
FROM `outgoing`
WHERE `business`=2 AND active = 'yes'
GROUP BY business
) AS b2
if you need the format
b1 | b2
300| 500
SELECT business, SUM(cost)
FROM mytable
GROUP BY
business
Try
SELECT business, SUM(cost) AS totalCost FROM myTable GROUP BY business
you can try this:
select
#num1:=(select sum(actor_id) from actor where actor_id%2=0)as number_1,
#num2:=(select sum(actor_id) from actor where actor_id%2!=0)as number_2,
#num1+#num2 as TOTAL;
or if you need active.
select
#num1:=(select sum(actor_id) from actor where actor_id%2=0 and active='yes')as number_1,
#num2:=(select sum(actor_id) from actor where actor_id%2!=0 and active='yes')as number_2,
#num1+#num2 as TOTAL;