Give the employee(fname and lname) that make the most money in each dept - each

SELECT max(salary), dept
FROM Employees
GROUP BY dept;
How to add fname and lname without the errors? If I add them in group by, I no longer get the max salary.

This is how I would do it in SQL Server... You need a subquery that returns the max salary for each department, then join that back to the employee table to figure out which employee has that salary for that department:
SELECT D.Dept, D.MaxSalary, Employees.FName, Employees.LName
FROM (
SELECT MAX(Salary) AS MaxSalary, Dept
FROM Employees
GROUP BY dept
) D
INNER JOIN Employees
ON Employees.Dept = D.Dept
AND Employees.Salary = D.MaxSalary

Related

DAX - distinct count of one column in permutations of other column

Given a set of data that has MRN (patient) and Dept as columns and where a patient can be seen in multiple Depts(many-to-many relationship), how can I put Dept across both row and column in pivot table and show how many distinct MRN were seen in each permutation of departments? I would also need to be able to compare groups of Dept - find distinct MRNs for one at least one Dept in a group of Depts that were also seen in at least one Dept from a different group of Depts. Hopefully the right DAX measure would accommodate this.
I've found suggestions for related questions to create a calculated column that is a copy of Dept, that way I can put Dept1 in row and Dept2 in column of a pivot table. However, I haven't figured out the DAX that will get distinct MRNs at each intersection of Depts.
Most promising, possible solution I've found is
DAX Measure to calculate the distinct feature counts across Manufacture & Products but I need to research CALCULATETABLE and SELECTEDVALUE more to know for sure.
[![Example][1]][1]
Here is some SQL that shows all Dept combinations and how many distinct MRNs for each combination, but it's limited to comparing two individual departments. I'd like to get this in DAX where the user could specify two individual departments, OR select a group of departments and find the distinct MRNs that were also seen in another group of departments.
; with Visits as (
select MRN = 'M00111', Dept = 'Apollo' union all
select MRN = 'M00111', Dept = 'EOB Ortho' union all
select MRN = 'M00111', Dept = 'EOB Ortho' union all
select MRN = 'M00222', Dept = 'EOB Gastro' union all
select MRN = 'M00333', Dept = 'EOB Neuro' union all
select MRN = 'M00333', Dept = 'NICU' union all
select MRN = 'M00444', Dept = 'EOB Cardio' union all
select MRN = 'M00444', Dept = 'NICU' union all
select MRN = 'M00444', Dept = 'EOB Cardio' union all
select MRN = 'M00444', Dept = 'EOB Neuro' union all
select MRN = 'M00555', Dept = 'Apollo'
)
--select * from Visits
, DistinctDepts as (
select distinct Dept from Visits
)
--select * from DistinctDepts
, AllDeptPermutations as (
select
Dept1 = dd1.Dept,
Dept2 = dd2.Dept
from
DistinctDepts dd1 join
DistinctDepts dd2 on 1 = 1
)
--select * from AllDeptPermutations
select
perms.*,
DistinctMrns = (
select
count(1)
from
(
select v1.MRN
from Visits v1
where v1.Dept = perms.Dept1
group by v1.Dept, v1.MRN
) dept1 join
(
select v2.MRN
from Visits v2
where v2.Dept = perms.Dept2
group by v2.Dept, v2.MRN
) dept2 on dept1.MRN = dept2.MRN
)
from
AllDeptPermutations perms
FOUND A SOLUTION: I decided to see what I could do in PowerBI. The example above is a simplified version, but in my actual project I have a fact table called Encounters and a dim table called Department and another dim table called Patients.
Solution: I made a copy of my fact table (Encounters2) and a copy of the Department dim table. I related Departments2 to Encounters2 and related Encounters2 to the Patients dim table. So, two identical fact tables related to the same Patients dim table, but also related to two different Department dimensions. I set the relationships from the two fact tables to the Patients table to both ways.
What this does is allows us to put two slicers on a matrix - one for each Department dim. With the relationships from each fact table going back to the Patients dim table, as each department dim filters each Encounters fact table, they essentially combine filters and propagate back to the Patients dim table. I put one Department dim as the X axis on the matrix and the other Department dim as the Y axis. I configured the slicers to allow multi-select, which means I can select one group of departments for the X axis of my matrix and select another group of departments for my Y axis of the matrix. A measure that gets distinct MRNs from the Patient dim table gives us the values we need - distinct patients that have been seen in two different groups of departments.
Not much DAX in this solution, but really just duplicating the fact table and one dimension and using two-way relationships. If someone knows a more elegant solution, I'd love to learn about it.

sqlite combine 2 queries from different tables to make one

I recently took to using sql again, the last time I used it was in microsoft access 2000 so please bear with me if I'm behind the times a little.
I have 2 pointless virtual currencies on my discord server for my players to play pointless games with. Both of these currencies' transactions are currently stored in individual tables.
I wish to sum up all the transactions for each player to give them a single current amount for each currency. Individually I can do this:
SELECT
tblPlayers.PlayerID AS PlayerID,
tblPlayers.Name AS Name,
SUM(tblGorillaTears.Amount)
FROM
tblPlayers
INNER JOIN
tblGorillaTears
ON
tblPlayers.PlayerID = tblGorillaTears.PlayerID
GROUP BY
tblPlayers.PlayerID;
and
SELECT
tblPlayers.PlayerID AS PlayerID,
tblPlayers.Name AS Name,
SUM(tblKebabs.Amount)
FROM
tblPlayers
INNER JOIN
tblKebabs
ON
tblPlayers.PlayerID = tblKebabs.PlayerID
GROUP BY
tblPlayers.PlayerID;
What i need is a table that outputs the user name the id and the total for each currency on one row, but when i do this:
SELECT
tblPlayers.PlayerID AS PlayerID,
tblPlayers.Name AS Name,
SUM(tblGorillaTears.Amount) AS GT,
0 as Kebabs
FROM
tblPlayers
INNER JOIN
tblGorillaTears
ON
tblPlayers.PlayerID = tblGorillaTears.PlayerID
GROUP BY
tblPlayers.PlayerID
UNION
SELECT
tblPlayers.PlayerID AS PlayerID,
tblPlayers.Name AS Name,
0 as GP,
SUM(tblKebabs.Amount)
FROM
tblPlayers
INNER JOIN
tblKebabs
ON
tblPlayers.PlayerID = tblKebabs.PlayerID
GROUP BY
tblPlayers.PlayerID;
the results end in a row for each player for each currency. How can i make it so both currencies appear in the same row?
Previously in MSAccess i was able to create two queries and then make a query of those two queries as if they were a table, but I cannot figure out how to do that in this instance. Thanks <3
UNION will add new rows for sure, you can try like following query.
SELECT TP.playerid AS PlayerID,
TP.NAME AS NAME,
(SELECT Sum(TG.amount)
FROM tblgorillatears TG
WHERE TG.playerid = TP.playerid) AS GT,
(SELECT Sum(TG.amount)
FROM tblkebabs TG
WHERE TG.playerid = TP.playerid) AS Kebabs
FROM tblplayers TP

Flexible search query using three tables

I have three tables Order,Customer,Address.
Edited :
I want to fetch all customer's who are registeretd with website.
If the customer has placed any order's i want to fetch the latest order from list of order's,
If customer has not placed any order then i want to put the field as blank as shown in below table
For eg :
Customer_Name Email ID Country Phone Latest_Order_Code
A xxxx xxxx x 1234
B yyyy yyyy y
C ffff tttt l 3456
D zzzz iiii o
Any help would be appreciated?
Refer to below query, where I have only fetch order code and Customer name. You can write more join and select fields based on your requirement.
select {o.code} as orderCode,
{c.name} as name,
{a.cellphone} as cellphone
from {order as o
join Customer as c on {c.pk} = {o.user}
join Address as a on {o.deliveryaddress} = {a.pk}
}
where {o.code} in ({{select max({code}) from {order} group by {user}}})
Update: Fetch all registered customers and their last order information
select t1.name, t2.orderCode, t2.cellphone
from
({{
select {pk} as userPk, {name} as name from {Customer}
}}) as t1
LEFT JOIN
({{
select
{o.code} as orderCode,
{o.user} as user,
{a.cellphone} as cellphone
from {order as o
join Address as a on {o.deliveryaddress} = {a.pk}
}
where {o.code} in ({{select max({code}) from {order} group by {user}}})
}}) as t2
on t2.user = t1.userPk
Detail post how to write complex flexible search query join using the dynamic tables?

SQ Server : how to find the fifth order for each customer

How to find the fifth order for each customer and return title_order or null if the customer doesn't have the fifth order
Tables are
customer with columns Id, firstname, lastname...
order with columns order_id, title_order, id_custmer, date...
It can be done only with a query or do I need to create a function
Thanks in advance
You can use OUTER APPLY with OFFSET-FETCH:
select c.firstname, oa.title_order
from customer c
outer apply(select title_order from order o
where o.id_custmer = c.Id
order by date
offset 4 ROW FETCH next 1 ROW only)oa

Nested Sum( ) query is not working in mysql

i'm having a problem in calculating total bill of a ptient. I have three tables named as "test", "pharmacy", "check".
Columns in test are:
patient_ID
testname
rate
Columns in pharmacy are:
patient_ID
medicineDescription
qty
rate
Columns in check are:
patient_ID
doctorID
fees
date
I have a table Bill that will store total amount of a patient.
patient_ID
amount
date
I have used the following query. But it's giving the following error.
$result = mysqli_query($data, "SELECT patient_ID, (SUM(pharmacy.qty*pharmacy.rate ) + SUM(test.rate) + SUM(check.fees))
AS total FROM pharmacy, test, check WHERE patient_ID= '$pID'" );
Correct query should be, closing bracket was missing at the end of subquery (... AS total FROM pharmacy**)**):
$result = mysqli_query ($data, "SELECT patient_ID,
(SUM(pharmacy.qty*pharmacy.rate ) + SUM(test.rate) + SUM(check.fees)) AS total FROM pharmacy),
test,
check
WHERE patient_ID= '$pID'" );
You have three tables in your from clause, but with no join condition - this means you're pairing each row with all the other rows, which is obviously not what you intended. One way to handle this is to use proper joins:
SELECT p.patient_id, pharmacy_sum + test_sum + fees_sum AS total
FROM (SELECT patient_id, SUM(qty * rate) AS pharmacy_sum
FROM pharmacy
WHERE patient_ID= '$pID'
GROUP BY patient_id) p
JOIN (SELECT patient_id, SUM(rate) AS test_sum
FROM test
WHERE patient_ID= '$pID'
GROUP BY patient_id) t ON p.patient_id_id = t.patient_id
JOIN (SELECT patient_id, SUM(fees) AS fees_sum
FROM check
WHERE patient_ID= '$pID'
GROUP BY patient_id) c ON p.patient_id_id = c.patient_id

Resources