MySQL select and count 2 colums with different where clauses - mysql

I think it should be very easy, but it didn't work at all. I have one table and I'd like to generate a chart which are displaying grouped items and with one where clause (column1) it should display the entries with status 0, and with the other where clause (column2) it should display the entries with status 1.
If I do the just one query it works fine, but I'd like to have both (status 0 and status 1) in one combined query.
Status 0 query:
SELECT item,quantity, COUNT(status) FROM `table`
WHERE `retry` = 1
AND `status` = 0
GROUP BY item,quantity
ORDER BY COUNT(status) DESC
Status 1 query:
SELECT item,quantity, COUNT(status) FROM `table`
WHERE `retry` = 1
AND `status` = 1
GROUP BY item,quantity
ORDER BY COUNT(status) DESC
My try to combine both (didn't work)
SELECT t1.item,t1.quantity, COUNT(t2.status), COUNT(t3.status) FROM `table` AS t1
LEFT JOIN (SELECT item,status FROM `table` WHERE `status` = '0' AND `retry` = 1 GROUP BY item,quantity) AS t2
ON t1.ndc = t2.ndc
LEFT JOIN (SELECT item,status FROM `table` WHERE `status` = '1' AND `retry` = 1 GROUP BY item,quantity) AS t3
ON t1.ndc = t3.ndc
WHERE 1
GROUP BY t1.item,t1.quantity
ORDER BY COUNT(t2.status) DESC

check this please , would it work for you?
please try this
SELECT
item,quantity,
COUNT(case when status =1 then 1 end) AS status1,
COUNT(case when status =0 then 1 end) AS status0
FROM table

SQL Fiddle Testdata:
CREATE TABLE testtable
(`id` int, `item` bigint(15), `quantity` double,`status` int(2),`retry` int(2))
;
INSERT INTO testtable
(`id`, `item`, `quantity`, `status`, `retry`)
VALUES
(1, '452457824', '1.0', '1', '1'),
(2, '452457824', '1.0', '1', '1'),
(3, '452457824', '0.5', '1', '1'),
(4, '452457824', '0.5', '0', '1'),
(5, '452457824', '0.5', '0', '1'),
(6, '452457824', '0.5', '0', '1'),
(7, '21432423', '1.0', '1', '1'),
(8, '21432423', '1.0', '1', '1'),
(9, '21432423', '1.0', '0', '1'),
(10, '21432423', '1.0', '0', '1'),
(11, '3455467567', '2.0', '1', '1'),
(12, '3455467567', '2.0', '1', '1'),
(13, '3455467567', '2.0', '0', '1'),
(14, '3455467567', '2.0', '0', '1'),
(15, '3455467567', '2.0', '0', '1'),
(16, '3455467567', '1.0', '1', '1'),
(17, '3455467567', '1.0', '1', '1'),
(18, '3455467567', '1.0', '1', '1')
;

Related

How to group a group and count the number of elements in this group sql

I am a beginner in sql and I am wondering how can I get the number of a group in a group.
Here I would like to group the table again according to the column "COL1" and then count the number of elements. This should output at the end that for the group B two is counted and for all others one.
For this first I created a table
CREATE TABLE tablename (`ID` INTEGER, `Col1` VARCHAR(1), `Col2` VARCHAR(1), `Col3` VARCHAR(6));
INSERT INTO tablename (`ID`, `Col1`, `Col2`, `Col3`) VALUES
('1', 'A', 'Q', 'green'),
('2', 'B', 'R', 'blue'),
('3', 'B', 'S', 'red'),
('4', 'C', 'T', 'purple'),
('5', 'D', 'U', 'orange'),
('6', 'E', 'R', 'black'),
('7', 'F', 'U', 'brown'),
('8', 'F', 'V', 'pink'),
('9', 'G', 'W', 'white'),
('10', 'B', 'R', 'blue');
and then I grouped the columns
SELECT count(*),Col1,GROUP_CONCAT(Col2) Col2,
GROUP_CONCAT(Col3) Col3
FROM tablename a
GROUP BY Col1, Col2
I hope I understood correctly what you want
select sum(sm),Col1,GROUP_CONCAT(Col2),GROUP_CONCAT(Col3) from (
SELECT count(*) as sm,Col1,GROUP_CONCAT(Col2) Col2,GROUP_CONCAT(Col3) Col3
FROM tablename a GROUP BY Col1, Col2
) b GROUP BY Col1

SQL find the difference in days between two case statements partitioned by users

Say I have a table like this:
http://sqlfiddle.com/#!9/800cb5
CREATE TABLE IF NOT EXISTS `transactions` (
`user_id` int(6) unsigned NOT NULL,
`created_at` datetime NOT NULL,
`bow` int(6) NOT NULL,
`eow` int(6) NOT NULL
) DEFAULT CHARSET=utf8;
INSERT INTO `transactions` (`user_id`, `created_at`, `bow`, `eow`) VALUES
('1', '2019-01-01', '0', '1'),
('1', '2019-01-02', '1', '1'),
('1', '2019-01-03', '1', '1'),
('1', '2019-01-05', '1', '0'),
('2', '2019-01-11', '1', '1'),
('1', '2019-02-01', '0', '1'),
('1', '2019-02-02', '1', '1'),
('1', '2019-02-03', '1', '0');
If the "bow" is equal to 0 when the "eow" is equal to 1, I want to start counting days. I want to stop counting when "bow" equals 1 and "eow" equals 0, then take the number of days between these two values.
So my output would be:
(`user_id`, `created_at`, `days`)
('1', '2019-01-05', '4')
('1', '2019-02-03', '2')
as there are 4 days between 2019-01-01 and 2019-01-05 and 2 days between 2019-02-01 and 2019-02-03.
You can use window functions -- specifically a cumulative conditional max() to get the previous date.
Then just filter for where the period ends:
select t.*,
datediff(created_at, prev_created_at)
from (select t.*,
max(case when bow = 0 and eow = 1 then created_at end) over (order by created_at) as prev_created_at
from transactions t
) t
where bow = 1 and eow = 0;
Here is a db<>fiddle.

Find records where condition met x number of times in mysql/sql

I'm struggling with what is a complicated SQL query for me, although I believe that it is not particularly complicated. I'm close to the right answer, but not quite there yet.
My database represents a criminal abstract. I have three tables in my database (I've simplified my schema enormously for the purposes of this question): arrest, arrestcharges, and dispositions.
Each defendant can have multiple arrests (defendant table not included for simplification). Each arrest can have multiple charges, which are in the arrestcharges table. And each charge has a grade and is associated with a disposition (guilty, not guilty, etc...). The dispositions are categorized so that 0=some form of guilt disposition, 1=a non-guilty disposition.
I want to find individuals who have been convicted of a charge graded as "M1" on more than one case. If an individual has been convicted of more than M1, but they are in the same case, that person shouldn't be returned (unless they have another case with an M1 conviction).
A sqlfiddle link and the SQL to create and populate the table is below.
I believe that this query should work, but it doesn't:
select a.defendantid, count(a.id)
FROM `arrest` AS a LEFT JOIN `arrestcharges` AS ac
ON a.id=ac.arrestid LEFT JOIN `dispositions` AS d
ON ac.dispositionid=d.id
WHERE d.dispocategory=0 AND ac.grade="M1"
GROUP BY a.id HAVING COUNT(a.id) > 1 ORDER BY a.defendantid;
Based on the sql below, I expect that defendant IDs 1 and 5 should be returned since they are the only two defendants with an M1 conviction in more than one arrest. But the actual response I am getting is 2 and 5. 2 should not be returned b/c defendant 2 only has one arrest in the database.
Any thoughts on what I am doing wrong?
SQLFiddle
CREATE TABLE IF NOT EXISTS `arrest` (
`id` int(6) unsigned NOT NULL,
`defendantid` int(6) unsigned NOT NULL,
`docketno` varchar(21) NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `arrestcharges` (
`id` int(6) unsigned NOT NULL,
`arrestid` int(6) unsigned NOT NULL,
`grade` varchar(2) NOT NULL,
`dispositionid` int(6) NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `dispositions` (
`id` int(6) unsigned NOT NULL,
`disposition` varchar(30) NOT NULL,
`dispoCategory` int(1) unsigned NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
INSERT INTO `arrest` (`id`, `defendantid`, `docketno`) VALUES
('1', '1', 'MC-51-CR-0000222-1999'),
('2', '1', 'MC-51-CR-0000223-1999'),
('3', '1', 'MC-51-CR-0000224-1999'),
('4', '2', 'MC-51-CR-0002343-2000'),
('5', '3', 'MC-51-CR-0002349-2000'),
('6', '3', 'MC-51-CR-0002350-2000'),
('7', '3', 'MC-51-CR-0002351-2010'),
('8', '3', 'MC-51-CR-0002352-2013'),
('9', '4', 'MC-51-CR-1209293-2011'),
('10', '5', 'MC-51-CR-2389848-1999'),
('11', '5', 'MC-51-CR-3893923-1999'),
('12', '5', 'MC-51-CR-2393912-1999');
INSERT INTO `dispositions` (`id`, `disposition`, `dispoCategory`) VALUES
('1', 'Guilty', '0'),
('2', 'Not Guilty', '1'),
('3', 'Guilty Plea', '0'),
('4', 'Dismissed', '1');
INSERT INTO `arrestcharges` (`id`, `arrestid`, `grade`, `dispositionid`) VALUES
('1', '1', 'M1', '1'),
('2', '1', 'M', '2'),
('3', '2', 'F', '2'),
('4', '2', 'M1', '3'),
('5', '3', 'M1', '1'),
('6', '4', 'M2', '4'),
('7', '4', 'M1', '3'),
('8', '4', 'M1', '3'),
('9', '4', 'M1', '1'),
('10', '5', 'M1', '2'),
('11', '6', 'M1', '2'),
('12', '7', 'F2', '1'),
('13', '8', 'F3', '1'),
('14', '9', 'M1', '2'),
('15', '9', 'M1', '2'),
('16', '9', 'M1', '2'),
('17', '9', 'M1', '2'),
('18', '10', 'M1', '1'),
('19', '10', 'M1', '1'),
('20', '11', 'M2', '3'),
('21', '12', 'M1', '4'),
('22', '12', 'M1', '3');
Try this query:
select a.defendantid, count(distinct(ac.arrestid)) as count
FROM `arrest` AS a LEFT JOIN `arrestcharges` AS ac
ON a.id=ac.arrestid LEFT JOIN `dispositions` AS d
ON ac.dispositionid=d.id
WHERE d.dispocategory=0 AND ac.grade="M1"
GROUP BY a.defendantid HAVING count>1;
You should count the distinct number as distinct_count of rows you need and make use of having filter such as having distinct_count>1. This way you can ensure that the count are not getting repeated.
You appear to be aggregating by the wrong column. You need a.defendantid in the group by:
SELECT a.defendantid, count(*)
FROM `arrest` a JOIN
`arrestcharges` ac
ON a.id = ac.arrestid JOIN
`dispositions` d
ON ac.dispositionid = d.id
WHERE d.dispocategory = 0 AND ac.grade = 'M1'
GROUP BY a.defendantid
HAVING COUNT(DISTINCT a.id) > 1
ORDER BY a.defendantid;
Note that I also changed the outer joins to inner joins. If charges and dispositions are not available, then your filtering conditions cannot be met. Hence, the appropriate join is an inner join.

SUM() Query Giving Wrong Results

I have three tables in my database - staff, salary, shift.
Shift table is linked to the staff table by the staff_id, and salary by the salary_band_id which is also in staff table.
I'm trying to calculate staffs wage by doing (Shift.Total_Hours * Salary.Hourly_Wage)
Here is my query:
SELECT Staff.First_Name, Staff.Last_Name, Shift.Staff_ID, Shift.Total_Hours, Sa.Hourly_Wage,
SUM(Shift.Total_Hours * Sa.Hourly_Wage) Total
FROM Shift, Salary Sa, Staff
INNER JOIN Salary ON Staff.Salary_Band_ID = Salary.Salary_Band_ID
WHERE Shift.Staff_ID = Staff.Staff_ID
GROUP by Staff_ID
ORDER BY Total;
Tables:
CREATE TABLE Shift (
Staff_ID INT(5) NOT NULL,
Date DATE NOT NULL,
Time_Started TIME NOT NULL,
Time_Ended TIME NOT NULL,
Total_Hours DOUBLE(4,2) NOT NULL,
Confirmed ENUM('y','n') NOT NULL
)
INSERT INTO Shift
(Staff_ID, Date, Time_Started, Time_Ended, Total_Hours, Confirmed)
VALUES
('1', '2012-06-08', '9:00', '16:45', '7.75', 'y'),
('3', '2012-06-18', '13:10', '17:30', '4.33', 'y'),
('6', '2012-10-14', '11:15', '16:45', '5.5', 'y'),
('4', '2012-10-30', '10:00', '17:00', '7', 'n'),
('5', '2013-07-15', '9:10', '17:20', '8.1', 'y'),
('10', '2013-08-10', '9:00', '17:00', '8', 'n'),
('8', '2013-10-05', '10:15', '17:30', '7.25', 'y'),
('7', '2013-11-06', '9:20', '17:00', '7.66', 'y'),
('2', '2014-03-25', '9:00', '16:45', '7.75', 'n'),
('9', '2014-04-11', '9:00', '17:00', '8', 'n'),
('11', '2014-06-05', '9:00', '17:00', '8', 'y');
CREATE TABLE Salary (
Salary_Band_ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
Position VARCHAR(40) NOT NULL,
Hourly_Wage DOUBLE(4,2) NOT NULL
)
INSERT INTO Salary
(Position, Hourly_Wage)
VALUES
('Worker', '6'),
('Worker Manager', '8'),
('General Manager', '10.22'),
('Manager', '13.45'),
('Owner', '25'),
('Brewer', '7.76'),
('Shop Assistant', '6.12');
CREATE TABLE Staff (
Staff_ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
Salary_Band_ID INT(5) NOT NULL,
First_Name VARCHAR(25) NOT NULL,
Last_Name VARCHAR(25) NOT NULL,
Part_Full_Time ENUM('f','p') NOT NULL,
DOB DATE NOT NULL,
Start_Date DATE NOT NULL,
End_Date DATE,
Address_ID INT(7) NOT NULL,
Contact_Number VARCHAR(12) NOT NULL,
Availability_ID INT(5) NOT NULL,
Brewery_ID INT(4),
Shop_ID INT(4)
)
INSERT INTO Staff
(Salary_Band_ID, First_Name, Last_Name, Part_Full_Time, DOB, Start_Date, Address_ID, Contact_Number, Availability_ID, Brewery_ID, Shop_ID)
VALUES
('1', 'Jenny', 'Bolick', 'p', '1966-08-15', '2005-06-06', '1', '+447700900969', '1', '1', '1'),
('2', 'Margit', 'Eves', 'f', '1968-01-13', '2005-10-06', '2', '07700900711', '1', '1', '2'),
('3', 'Ramonita', 'Layton', 'f', '1975-11-28', '2005-09-29', '3', '07700900336', '1', '1', '1'),
('4', 'Kattie', 'Speck', 'p', '1977-10-24', '2006-09-07', '6', '07700900615', '1', '1', '2'),
('5', 'Christa', 'Denk', 'p', '1968-03-25', '2008-04-11', '5', '07700900542', '2', '2', '4'),
('6', 'Francene', 'Scholl', 'p', '1991-08-05', '2009-05-06', '12', '07700900763', '2', '1', '4'),
('7', 'Patti', 'Tomaszewski', 'f', '1974-01-22', '2010-03-11', '11', '07700900125', '3', '2', '6'),
('7', 'Pandora', 'Laplant', 'p', '1982-02-14', '2011-10-03', '11', '+447700900118', '2', '3', '5'),
('1', 'Branden', 'Bermejo', 'f', '1985-08-15', '2012-04-18', '10', '07700900687', '4', '3', '6'),
('1', 'Lanell', 'Delao', 'p', '1987-12-24', '2012-04-20', '9', '07700900057', '5', '3', '2'),
('1', 'Floria', 'Vandermark', 'f', '1991-03-13', '2013-11-13', '6', '07700900396', '6', '4', '2');
The results all look OK, except the Totals are way off! Also it seems to only pick one salary_band.. £6.60/hour Can anyone see what I'm doing wrong?
I think this is what you are looking for, use explicit JOIN instead of implicit.
SELECT
st.First_Name,
st.Last_Name,
sh.Staff_ID,
sh.Total_Hours,
sa.Hourly_Wage,
SUM(sh.Total_Hours * sa.Hourly_Wage) Total
from Staff st
inner join Salary sa on sa.Salary_Band_ID = st.Salary_Band_ID
inner join Shift sh on sh.Staff_ID = st.Staff_ID
GROUP by st.Staff_ID
ORDER BY Total
desc
;
DEMO

rank users and join tables

How do I rank users based on points and join that user_sno with refno of another table?
I am not getting right ranking with the code below :
select *, (#rank := #rank + 1) as rank
from tblB uv
join tblC c on uv.sno=c.refno
join
(select #rank := 0) const
where uv.sno in (2, 4,5)
order by rank;
I really appreciate any help.Thanks in Advance.
http://sqlfiddle.com/#!2/9be59/12
CREATE TABLE if not exists tblB
(
id int(11) NOT NULL auto_increment ,
sno varchar(255),
name varchar(255),
PRIMARY KEY (id)
);
CREATE TABLE if not exists tblC
(
id int(11) NOT NULL auto_increment ,
data varchar(255),
refno varchar(255),
points int(255),
PRIMARY KEY (id)
);
INSERT INTO tblB (sno, name ) VALUES
('1', 'Aa'),
('2', 'Bb'),
('3', 'Cc'),
('4', 'Dd'),
('5', 'Ee'),
('6', 'Ff'),
('7', 'Gg'),
('8', 'Hh');
INSERT INTO tblC (data,refno,points ) VALUES
('data1', '1', '101'),
('data2', '2', '102'),
('data3', '3', '103'),
('data4', '4', '101'),
('data5', '5', '102'),
('data6', '6', '103'),
('data7', '7', '101'),
('data8', '8', '101'),
('data9', '9', '101');
You ORDER BY rank, but you want to ORDER BY points, seems like a typo.