Sum does'nt work for multiply - mysql

SELECT Sum((pvc.cpt_amount) * (pvc.unit)) AS billed_amount,
pvc.cpt_amount,
pvc.unit
FROM payment AS pay
LEFT JOIN patient_insurances AS pi
ON pay.who_paid = pi.id
LEFT JOIN patient_visit_cpt AS pvc
ON (
pay.encounter_id = pvc.id
AND pay.claim_id = pvc.claim_id )
LEFT JOIN patient_visit AS pv
ON pvc.visit_id = pv.id
WHERE
and pi.insurance_id = 761
AND pay.created_at <= '2016-04-01 23:00:00'
AND pay.created_at >= '2016-03-31 00:00:00'
GROUP BY pay.check_number,
pv.attending_provider_id
for unit = 1 and cpt_amount = 145, but output comes like
mulitplied with 4. like 1 * 145 = 580.. please any one give solution

Your Group By might be wrong.
Also remove keyword AND after the WHERE Clause
Try below query
SELECT Sum((pvc.cpt_amount) * (pvc.unit)) AS billed_amount,
pvc.cpt_amount,pvc.unit
FROM payment AS pay
LEFT JOIN patient_insurances AS pi ON pay.who_paid = pi.id
LEFT JOIN patient_visit_cpt AS pvc ON(pay.encounter_id = pvc.id AND pay.claim_id = pvc.claim_id)
LEFT JOIN patient_visit AS pv ON pvc.visit_id = pv.id
WHERE pi.insurance_id = 761 AND pay.created_at <= '2016-04-01 23:00:00'
AND pay.created_at >= '2016-03-31 00:00:00'
GROUP BY pvc.cpt_amount,pvc.unit

Related

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

Error Code: 1242 Subquery returns more than 1 row

Got problem, I am trying to calculate of each employee Total_Hours but when am grouping it comes up with an error. However, I know what the problem is but i am not sure how to fix it.
Select
tt.uid as 'Employee',
if (tc.organisation like '%Village%' or tc.organisation like '%Personnel%', 'Village', 'Client' ) as 'Type of work',
round((sum(timestampdiff(minute, start_time, end_time))/60),2) AS 'Hours',
(select
round((sum(timestampdiff(minute, start_time, end_time))/60),2)
from timesheet.timesheet_times ttt
left outer join timesheet.timesheet_project ttp on ttt.proj_id = ttp.proj_id
left outer join timesheet.timesheet_client ttc on ttp.client_id = ttc.client_id
where
month(ttt.start_time) = month(now())
and year(ttt.start_time) = year(now())
group by
ttt.uid
)as TOTAL_HOURS_PER_EMPLOYEE,
round((
(round((sum(timestampdiff(minute, start_time, end_time))/60),2)
/
(select
round((sum(timestampdiff(minute, start_time, end_time))/60),2)
from timesheet.timesheet_times ttt
left outer join timesheet.timesheet_project ttp on ttt.proj_id = ttp.proj_id
left outer join timesheet.timesheet_client ttc on ttp.client_id = ttc.client_id
where
month(ttt.start_time) = month(now())
and year(ttt.start_time) = year(now()))
)*100),0) as percentage
from
timesheet.timesheet_times tt
left outer join timesheet.timesheet_project tp on tt.proj_id = tp.proj_id
left outer join timesheet.timesheet_client tc on tp.client_id = tc.client_id
where
month(tt.start_time) = month(now())
and tc.organisation not like '%Private%'
and year(tt.start_time) = year(now())
group by
tc.client_id
order by
round((sum(timestampdiff(minute, start_time, end_time))/60),2) desc
I am sorry if I wrote that post wrong, it's my first time on here or asked for help.

How to order by number of sold products during a date?

I need to order a result by number of sold products.
Here is an extract from my (complex) SQL:
SELECT ....
SUM(products.quantity) as numberSold,
....
ORDER by numberSold
How can I order by sold items ONLY during this year ?
I tried with
HAVING products.products.date>'01-01-2015', but it affcts the number of returned rows.
Here is the indigest SQL I did not write and that I have to change:
Select Distinct
boutique_produit.*,
boutique_produit_description.*,
boutique_produit_plus.*,
Sum(boutique_commande_detail.quantite) As numberSold
From
boutique_categorie Inner Join
boutique_categorie_produit On boutique_categorie_produit.boutique_categorie_id
= boutique_categorie.id_boutique_categorie Inner Join
boutique_produit On boutique_produit.id_boutique_produit =
boutique_categorie_produit.boutique_produit_id And
boutique_produit.zone_id = boutique_categorie_produit.zone_id Inner Join
boutique_produit_description
On boutique_produit_description.boutique_produit_id =
boutique_produit.id_boutique_produit And
boutique_produit_description.zone_id = boutique_categorie_produit.zone_id
And (boutique_produit_description.boutique_langue_disponible_code = 'FR')
Inner Join
boutique_produit_reference On boutique_produit_reference.boutique_produit_id =
boutique_produit.id_boutique_produit And boutique_produit_reference.zone_id
= boutique_categorie_produit.zone_id Inner Join
boutique_produit_reference_prix
On boutique_produit_reference_prix.boutique_produit_reference_id =
boutique_produit_reference.id_boutique_produit_reference And
boutique_produit_reference_prix.zone_id = boutique_categorie_produit.zone_id
Inner Join
boutique_taxe On boutique_taxe.id_boutique_taxe =
boutique_produit_reference.boutique_taxe_id Inner Join
boutique_produit_plus On boutique_produit_plus.boutique_produit_id =
boutique_produit.id_boutique_produit And boutique_produit_plus.zone_id =
boutique_categorie_produit.zone_id Inner Join
boutique_produit_plus_categories
On boutique_produit_plus_categories.boutique_produit_id =
boutique_produit_plus.boutique_produit_id And
boutique_produit_plus_categories.zone_id = boutique_produit_plus.zone_id And
(boutique_produit_plus_categories.categorie_id In (1750, 1227, 1880))
Inner Join
poi On boutique_produit_plus.poi_id = poi.ID_poi And poi.zone_id =
boutique_categorie_produit.zone_id And (((poi.payant = 1 And
('2015-12-10' >= poi.dateDebutValidite) And ('2015-12-10' <=
poi.dateFinValidite)) Or (poi.illimite = 1))) Inner Join
boutique_professionnel On poi.boutique_professionnel_id =
boutique_professionnel.id_boutique_professionnel And
boutique_professionnel.zone_id = poi.zone_id And
(boutique_professionnel.compte_actif = 1) Left Join
boutique_commande_detail
On boutique_commande_detail.boutique_produit_reference_id =
boutique_produit_reference.id_boutique_produit_reference And
boutique_commande_detail.zone_id = boutique_categorie_produit.zone_id
Where
boutique_categorie_produit.boutique_categorie_id = 382 And
(boutique_produit_plus.date_fin_valid = '' Or
boutique_produit_plus.date_fin_valid Is Null Or
boutique_produit_plus.date_fin_valid >= '2015-12-10 23:59:59') And
boutique_produit.produit_actif = 1 And
boutique_categorie_produit.zone_id = 4
Group By
boutique_produit.id_boutique_produit, boutique_produit.zone_id
Order By
numberSold Desc
Limit 0, 60
numberSold is the IMPORTANT field
use the WHERE clause on products.date
If I understand you correctly, you want to sum products.quantity only when products.date>'01-01-2015', and if the date is lower you want to exclude that quantity? Then try CASE.
SELECT ....
SUM(CASE WHEN products.date>'01-01-2015' THEN products.quantity
ELSE 0
END) as numberSold,
....
ORDER by numberSold

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.

Only getting one result from sub select in inner join in mysql

Hi I have run into a dilemma, I am doing this query:
SELECT GROUP_CONCAT(DISTINCT(ca.category_name) SEPARATOR ', ') AS categories, pr.promo_name, pr.add_value_text, c.contract_id, c.cmeal_plan, c.cmin_markup, c.civa, c.tax_include, c.hotel_id, hi.hname, hi.hstars, im.image_file, pl.plan_name, ra.price
FROM contracts AS c
INNER JOIN hotel_info AS hi ON hi.hotel_id = c.hotel_id AND hi.destination_id = '6460'
INNER JOIN images AS im ON im.foreign_id = hi.hotel_id
INNER JOIN meal_plan AS pl ON pl.plan_code = c.cmeal_plan AND pl.lang = '1'
INNER JOIN hotel_categories AS hc ON hc.hotel_id = hi.hotel_id
INNER JOIN categories AS ca ON ca.category_code = hc.category_code AND ca.lang = '1'
LEFT JOIN
(SELECT
r.hotel_id, AVG(r.double) AS price
FROM
rates AS r ) AS ra
ON ra.hotel_id = hi.hotel_id
LEFT JOIN promotions AS pr ON pr.hotel_id = hi.hotel_id AND FIND_IN_SET(c.contract_id, pr.contract_id) > 0 AND pr.book_start <= '2012-11-01' AND pr.book_end >= '2012-11-02' AND travel_start <= '2012-11-23' AND travel_end >= '2012-11-30' AND pr.lang = '1'
WHERE c.cstart <= '2012-11-01' AND c.cend >= '2012-11-01'
AND hi.status = '1'
AND im.type ='1'
GROUP BY hi.hotel_id
I am getting all the desired results except for the sub select query.. each hotel has a price but it is only giving me back one result and the rest are all null. Is there an error in my query? If any additional information is needed please let me know and thank you in advance for any help!
You are missing the GROUP BY in your subquery, so MySQL will only return one-value. If you want all hotel_id's then you need to GROUP BY that field:
SELECT GROUP_CONCAT(DISTINCT(ca.category_name) SEPARATOR ', ') AS categories,
pr.promo_name,
pr.add_value_text,
c.contract_id,
c.cmeal_plan,
c.cmin_markup,
c.civa,
c.tax_include,
c.hotel_id,
hi.hname,
hi.hstars,
im.image_file,
pl.plan_name,
ra.price
FROM contracts AS c
INNER JOIN hotel_info AS hi
ON hi.hotel_id = c.hotel_id
AND hi.destination_id = '6460'
INNER JOIN images AS im
ON im.foreign_id = hi.hotel_id
INNER JOIN meal_plan AS pl
ON pl.plan_code = c.cmeal_plan
AND pl.lang = '1'
INNER JOIN hotel_categories AS hc
ON hc.hotel_id = hi.hotel_id
INNER JOIN categories AS ca
ON ca.category_code = hc.category_code
AND ca.lang = '1'
LEFT JOIN
(
SELECT r.hotel_id, AVG(r.double) AS price
FROM rates AS r
GROUP BY r.hotel_id <-- add a GROUP BY hotel_id then you will get avg() for each hotel
) AS ra
ON ra.hotel_id = hi.hotel_id
LEFT JOIN promotions AS pr
ON pr.hotel_id = hi.hotel_id
AND FIND_IN_SET(c.contract_id, pr.contract_id) > 0
AND pr.book_start <= '2012-11-01'
AND pr.book_end >= '2012-11-02'
AND travel_start <= '2012-11-23'
AND travel_end >= '2012-11-30'
AND pr.lang = '1'
WHERE c.cstart <= '2012-11-01'
AND c.cend >= '2012-11-01'
AND hi.status = '1'
AND im.type ='1'
GROUP BY hi.hotel_id