Selecting only max column - mysql

I'm trying to select only a max column by grade_level. If I select a column that is less than max column by grade_level should not be selected.
CREATE TABLE sample
(
name VARCHAR(50),
grade_level INT,
money INT
);
INSERT INTO sample (name, grade_level, money) VALUES
("John", 1, 100),
("John", 2, 200),
("John", 2, 250),
("Shadow", 1, 110),
("Shadow", 2, 300);
SELECT * FROM sample;
name | grade_level | money
John 1 100
John 2 200
John 2 250
Shadow 1 110
Shadow 2 300
This is my sample query so far while working on it.
SELECT name
, max(money)
FROM sample
WHERE grade_level = (SELECT max(grade_level) FROM sample WHERE grade_level = 2)
GROUP BY name;
Output:
name | money
John 250
Shadow 110
As you can see here if I put grade_level as 2 in my WHERE CLAUSE it gives me a right value. But how can avoid selecting other column if I put grade_level as 1 because I'm only selecting the max column.

Something simple like this will work :
select name, max(money)
from sample
group by grade_level
Use grade_level in GROUP BY clause instead of name

i think this what you are expecting let me know if i am wrong
SELECT name, max(money),grade_level FROM sample
GROUP BY name,grade_level;
i created a fiddle for your answer check it out : http://sqlfiddle.com/#!9/48022b/4
EDIT :
try this :
SELECT name, max(money) FROM sample
WHERE grade_level = (SELECT max(grade_level) FROM sample)
and grade_level = 2
GROUP BY name;
check the fiddle for more info http://sqlfiddle.com/#!9/48022b/11

Related

select query which matches name in input query

**id eid name value**
8 1 bbbb 3433
7 1 abce 1234
6 1 abcd efgh
Need to select value which has name = bbbb and abce.
I tried below query:
select * from emp where name in("bbbb","abce");
I am getting result as expected.
But if my query is below:
select * from emp where name in("bbbb","abce","abc");
my expected output is empty result because there is no name matches as abc in my above table.
But i am getting result which matches bbbb and abce.
What you do is simply select rows with a filter that uses the IN operator, but you requirement is different.
First get the eids that contain all the names in the list and then filter:
select * from emp
where name in('bbbb', 'abce', 'abc')
and eid in (
select eid from emp
where name in('bbbb', 'abce', 'abc')
group by eid
having count(distinct name) = 3
);
Check the demo.
A query:
select * from emp where name in("bbbb","abce","abc");
means that find emp's where name is any of those listed: bbbb or abce or abc
If you want to find emp's where each name listed appears at least once
select *
from emp
where name in("bbbb","abce","abc") and 3 = (
select count(distinct name)
from emp
where name in("bbbb","abce","abc")
)
IF you expect no result means you need to use AND condition :
select * from emp where name = "bbbb" and name="abce" and name = "abc";

query select max with mixed string and int

I have a table which contain a column for generated code, the data type is VARCHAR with mixed string/int values like :
Table demo
ID code
==============
1 | 001qwe
2 | 002qwe
3 | 001asd
Question :
1. How to get max value that contain qwe or asd, i want it used as filter.
2. How to get id of row which contain the maxed value
i want something like :
select *,MAX(SUBSTRING(code, 1, 3)) from demo where SUBSTRING(code, 4, 3) = 'asd'
Yes this case code length is 6 and number is 3 digit in the beginning of data
Considering above you can write your query as below
select *,left(`code`,3)
from demo
order by left(`code`,3) * 1 desc
limit 1
DEMO
to get individual results you can use following
SELECT a.id qweid, a.code qwecode,b.id asdid,b.code asdcode
FROM
(SELECT id,`code`
FROM demo
WHERE RIGHT(`code`,3) = 'qwe'
ORDER BY LEFT(`code`,3) * 1 DESC
LIMIT 1) a
CROSS JOIN(SELECT id,`code`
FROM demo
WHERE RIGHT(`code`,3) = 'asd'
ORDER BY LEFT(`code`,3) * 1 DESC
LIMIT 1) b
DEMO

SQL: Group by - further attribute with largest quantity

I'm new to SQL and facing following problem:
This is my table:
name city people
-----|-----|--------|
John | A | 5 |
Ben | D | 6 |
John | A | 5 |
Ben | A | 5 |
John | B | 8 |
Ben | D | 6 |
I want to group by the name and receive associated to the name that city with the largest quantity. As a second query, instead of the largest quantity, that city with the highest sum of inhabitants.
This would be the outcome for the first query:
name city
-----|-----|
John | A |
Ben | D |
Thank you!
I don't know exactly what you mean by "to the name that city with the largest quantity". What I understood was you sum the column 'people' per couple (name, city), thus (John, A) would be 10 and (John, B) would be 8, and you take the max value to get (John, A).
In this case, you can do it this way:
SELECT
name,
city
FROM
(SELECT
name,
city,
SUM(people) AS tot
FROM table
GROUP BY name, city
ORDER BY name ASC, tot DESC) AS a
GROUP BY name ;
As for the city with the largest number of inhabitants, you just have to group by city and sum the column people and take the max:
SELECT
city,
SUM(people) AS nb_inhabitants
FROM table
GROUP BY city
ORDER BY nb_inhabitants DESC
LIMIT 1;
SELECT name, city, sum( people )
FROM `detail`
GROUP BY name
ORDER BY people ASC
LIMIT 0 , 30
I am not really understand what your are expecting ,but I guess you want to do this thing.
Description : I am group by people from there name , and got sum of the people and make them ASC order. I am not sure your are expect this thing.
You can also , group people by their city
SELECT name, city, sum( people )
FROM `detail`
GROUP BY city
ORDER BY people ASC
LIMIT 0 , 30
If this not you expect , Please , further describe question ,we will try to give some answer.
Try this, I have tried by making a table as per your sample data,
CREATE TABLE KaiTable
(
NAME VARCHAR(50)
,city CHAR(1)
,people INT
);
INSERT INTO KaiTable
VALUES
(
'John'
,'A'
,5
),
('Ben ' ,'D' ,6),
('John' ,'A' ,5),
('Ben ' ,'A' ,5) ,
('John' ,'B' ,8) ,
('Ben ' ,'D' ,6)
SELECT NAME,city
FROM
(SELECT NAME,city,SUM(people) AS PeopleSum
FROM KaiTable
GROUP BY NAME, city
ORDER BY NAME ASC, PeopleSum DESC) AS a
GROUP BY NAME DESC;
SQL Fiddle Demo

Order MySql query using

I, I would like to make a query and sorting my members in a special way... Could someone help ?
Here's the problem.
I would like to select members in my table using a special sort order.
The profile fields values are stored in a table wp_bp_xprofile_data like this :
id | field_id | user_id | value
--------+----------+---------+----------
For example, I have 3 fields
NICKNAME (field_id = 1)
FIRSTNAME (field_id = 2)
LASTNAME (field_id = 3)
The table rows will look like this :
id | field_id | user_id | value
--------+----------+---------+----------
2544 1 100 fib
2545 2 100 john
2546 3 100 arenzich
2547 1 200 dog
2548 2 200 rick
2549 3 200 zarenburg
2550 1 300 fox
2551 2 300 frank
2552 3 300 arenzich
I've got this query to sort them using one field, for example to sort them by nickname alphabetically :
SELECT *
FROM wp_bp_xprofile_data u WHERE u.field_id = 1 ORDER BY u.value ASC
So they will be sorted like this : dog(200),fib(100), then fox(300).
Now, I would like to sort them not one but several fields (firstname and lastname; to differenciate people with same lastname) so that the query returns the users in this order :
frank arenzich (300), john arenzich (100), frank arenzich (200).
Any idea for doing this ?
Thanks A LOT !!!
This will probably need to be done by first pivoting this into a proper table by column, and then ordering that on multiple columns.
Note: this will not produce output in the same format as your original table, but is arguably a lot more flexible and useful as it combines all information about each user_id into a single row.
/* A column-wise pivot of NICKNAME, FIRSTNAME, LASTNAME */
SELECT
user_id,
MAX(CASE WHEN field_id = 1 THEN value ELSE null END) AS NICKNAME,
MAX(CASE WHEN field_id = 2 THEN value ELSE null END) AS FIRSTNAME,
MAX(CASE WHEN field_id = 3 THEN value ELSE null END) AS LASTNAME
FROM wp_bp_xprofile_data
GROUP BY user_id
/* Include the HAVING if you only want those who have both first & last names specified */
HAVING
FIRSTNAME IS NOT NULL
AND LASTNAME IS NOT NULL
/* Pivoted columns can then be treated in the ORDER BY */
ORDER BY
FIRSTNAME,
LASTNAME
Here is a demonstration...
It looks like this is a Wordpress table, so you may not be in a position to change its structure. But if you do have the option of modifying it, I would recommend changing the structure to resemble the pivot's output to begin with.

How to get ID for INSERT if name already used, else generate new one

I'm having a bit of trouble with an INSERT query.
I have a table I'm inserting a value into that's like this:
TABLE cars
ID Brand Model B_ID
---------------------------
1 Ford Escort 1
2 Ford Focus 1
3 Nissan Micra 2
4 Renault Megane 3
5 Ford Mustang 1
ID is unique and B_ID is the same ID for every same brand.
When inserting a new entry I want to be able to check if a brand is already in there and use that same B_ID otherwise I want to increment the highest B_ID and insert that.
I've got this far:
INSERT INTO 'cars' ('brand', 'model', 'B_ID')
VALUES (
'Nissan'
'Note'
'SELECT B_ID FROM cars WHERE brand = 'Nissan'
)
How can I get the highest B_ID and increment it by one if there is no match with my subquery because it's a new brand?
I'm using MySQL.
INSERT INTO `cars` (`brand`, `model`, `B_ID`)
select 'Nissan', 'Note', coalesce(Max(B_ID),0)+1 FROM cars WHERE brand = 'Nissan'
Until you normalize your tables:
INSERT INTO cars
(brand, model, B_ID)
SELECT 'Nissan'
, 'Note'
, COALESCE( ( SELECT B_ID
FROM cars
WHERE brand = 'Nissan'
LIMIT 1
)
, ( SELECT MAX(B_ID)
FROM cars
) + 1
, 1 --- this is for the case when the table is empty
)
Also notice that if you have multiple concurrent INSERT, you may end with rows that have different brand but same B_ID.