I have a small problem regarding a count after grouping some elements from a mysql table,
I have an orders table .. in which each order has several rows grouped by a code (named as codcomanda) ... I have to do a query which counts the number of orders per customer and lists only the name and number of orders.
This is what i came up (this might be dumb ... i'm not a pro programmer)
SELECT a.nume, a.tel, (
SELECT COUNT(*) AS `count`
FROM (
SELECT id AS `lwtemp`
FROM lw_comenzi_confirmate AS yt
WHERE status=1 AND yt.tel LIKE **a.tel**
GROUP BY yt.codcomanda
) AS b
) AS numar_comenzi
FROM lw_comenzi_confirmate AS a
WHERE status=1
GROUP BY tel;
nume = NAME
tel = PHONE (which is the distinct identifier for clients since there's no login system)
The problem with the above query is that I don't know how to match the a.tel with the one on which the first select is on. If I replace it with a number that is in the db it works....
Can anyone help me one how to refer to that var?
or maybe another solution on how to get this done?
If any more info is needed I`ll provide asap.
Please, correct me if I'm wrong in my understanding of your schema:
lw_comenzi_confirmate contains nume and tel of the customer;
lw_comenzi_confirmate contains order details (same table);
one order can have several entries in the lw_comenzi_confirmate table, order is distinguished by codcomanda field.
First, I highly recommend reading about Normalisation and fixing your database design.
The following should do the job for you:
SELECT nume, tel, count(DISTINCT codcomanda) AS cnt
FROM lw_comenzi_confirmate
WHERE status = 1
GROUP BY nume, tel
ORDER BY nume, tel;
You can test this query on SQL Fiddle.
Related
I've made a table with the columns for a customer name and each activity they participate in. How can I can I count the activities for each name and display it?
I've done;
SELECT Activity_Name, COUNT(*) AS 'Number_of_activities'
FROM tablename
GROUP BY Activity_Name;
which gives me each a table of each activity and how many participants in each activity but not each customer and their number of activities
Apologies for anything I've done wrong, only a couple months into coding and first time posting on stack...
Considering I don't know how your schema looks exactly, this query should be a nice representation of the idea how to do it:
SELECT customer_name, COUNT(*) AS 'Number_of_activities_per_customer'
FROM tablename
GROUP BY customer_name;
I have a task to make a database only in MySQL. I made 11 tables and connected them via foreign keys. I tried to make a simple query in order to return name and lastname of the patient in his diagnose, but I always get only a header with the first and last name and analysis.
The patient's table has nameID, name, last name, ID serial number, date of birth and so on, but I wanted only name and last name for the test query.
The second table I joined is analysis, which has analysisID, patientID, doctorID, hospitalID, diagnosis and so on.
My query is like this:
SELECT pat.name, pat.lastname
FROM patient pat
JOIN analysis a ON pat.patientID = a.patientID
group by a.analysisID
order by pat.lastname
This query returns 0 rows. Please help, I am new at mySQL. I read a lot of tutorials, read posts here about this problem and I still didn't find a solution.
I assume that you want to eliminate any duplicate analysisID's for the same person with the use of group by. If so, you could use the following:
Select a.analysisID, pat.name, pat.lastname
from patient pat, analysis a
where pat.patientID = a.patientID
group by a.analysisID, pat.name, pat.lastname
What the above query will do is return only one record when the analysisID, name and lastname are all the same.
I am trying to retrieve the the first row among the duplicate row, THE FIRST OCCURED ***
--Table--
Order_No Product User
1 Book Student
2 Book Student
3 Book Student
I want to get the Order_No of the first duplicate row in JAVA, I have used DISTINCT and DISTINCT TOP 1 etc but nothing worked, NEED HELP
SELECT min(order_no), product, user
FROM 'table'
GROUP BY user, product
This is basic SQL?
SELECT min(order_no), product, user FROM table GROUP BY product, user
See also more information on GROUP BY
All fields not part of your group by must have some sort of way to determine which to pick of the n potentially different values. min() will pick the lowest value (even with strings and dates) while max() will pick the highest. You can also use First() and Last() to grab the value according to when they show up.
Supposing you had other values to pick from, you might see something like:
SELECT min(order_no), product, user, min(creation_date),
sum(quantity), first(billing_address)
FROM orders GROUP BY product, user
SELECT t.*
FROM table t
WHERE NOT EXISTS ( SELECT a
FROM table t2
WHERE t2.Product = t.Product
AND t2.User = t.User
AND t2.Order_No < t.Order_No
)
I have a Table containing columns Email, Ip, State, City, TimeStamp, Id
I need to count where Email and IP are distinct, group by State
So when I run a MYSQL query,
select State, City ,count(distinct( Email )), count(DISTINCT( IP))
from table
group by Stat, City
It gives me distinct of each, but not AND
I need a count of distinct Email && Distinct IP ; grouped by State, City.
And distincts cant be within the Group, it has to be the 1st instance of EMAIL, and first instance of IP in entire database. So if i expand it, and add a date parameter, even though im selecting a specific date, I still can check whole database for the uniques.
So if i need
select state, city, count ( distinct ( IP ) , count ( distinct ( EMAIL ))
from table
where timestamp > date(2014-12-01)
group by state, city
What type of query is this? And how can I accomplish this?
My gut tells me i need to do CONCAT as suggested, but also another select inside. So select whole database distinct ip, then select that specific criteria from the other select.
This can help a bit to have a "distinct(A && B)"
SELECT DISTINCT(CONCAT(A,'_',B)),C,D
FROM table
GROUP BY C,D
We struggled to do this on a production server and found the query required was too resource intensive. So we created a table with an update on first instance the item occurs, then we check for counts with a join like so:
select count(a.State) from tablename A
inner join table_update U
on a.id = u.id
WHERE a.parameters..
and c.first_email = 1
and c.first_ip = 1
We couldnt find a single table that wouldnt bring our server down with 400,000 records. Its not a classy answer, but its what we had to use.
Within my J2EE web application, I need to generate a bar chart representing the percentage of users in the system with specific alerts. (EDIT - I forgot to mention, the graph only deals with alerts associated with the first situationof each user, thus the min(date) ).
A simplified (but structurally similar) version of my database schema is as follows :
users { id, name }
situations { id, user_id, date }
alerts { id, situation_id, alertA, alertB }
where users to situations are 1-n, and situations to alerts are 1-1.
I've omitted datatypes but the alerts (alertA and B) are booleans. In my actual case, there are many such alerts (30-ish).
So far, this is what I have come up with :
select sum(alerts.alertA), sum(alerts.alertB)
form alerts, (
select id, min(date)
from situations
group by user_id) as situations
where situations.id = alerts.situation_id;
and then divide these sums by
select count(users.id) from users;
This seems far from ideal.
Your recommendations/advice as to how to improve as query would be most appreciated (or maybe I need to re-think my database schema)...
Thanks,
Anthony
PS. I was also thinking of using a trigger to refresh a chart specific table whenever the alerts table is updated but I guess that's a subject for a different query (if it turns out to be problematic).
At first, think about your schema again. You will have a lot of different alerts and you probably don't want to add a single column for every one of those.
Consider changing your alerts table to something like { id, situation_id, type, value } where type would be (A,B,C,....) and value would be your boolean.
Your task to calculate the percentages would then split up into:
(1) Count the total number of users:
SELECT COUNT(id) AS total FROM users
(2) Find the "first" situation for each user:
SELECT situations.id, situations.user_id
-- selects the minimum date for every user_id
FROM (SELECT user_id, MIN(date) AS min_date
FROM situations
GROUP BY user_id) AS first_situation
-- gets the situations.id for user with minimum date
JOIN situations ON
first_situation.user_id = situations.user_id AND
first_situation.min_date = situations.date
-- limits number of situations per user to 1 (possible min_date duplicates)
GROUP BY user_id
(3) Count users for whom an alert is set in at least one of the situations in the subquery:
SELECT
alerts.type,
COUNT(situations.user_id)
FROM ( ... situations.user_id, situations.id ... ) AS situations
JOIN alerts ON
situations.id = alerts.situation_id
WHERE
alerts.value = 1
GROUP BY
alerts.type
Put those three steps together to get something like:
SELECT
alerts.type,
COUNT(situations.user_id)/users.total
FROM (SELECT situations.id, situations.user_id
FROM (SELECT user_id, MIN(date) AS min_date
FROM situations
GROUP BY user_id) AS first_situation
JOIN situations ON
first_situation.user_id = situations.user_id AND
first_situation.min_date = situations.date
GROUP BY user_id
) AS situations
JOIN alerts ON
situations.id = alerts.situation_id
JOIN (SELECT COUNT(id) AS total FROM users) AS users
WHERE
alerts.value = 1
GROUP BY
alerts.type
All queries written from my head without testing. Even if they don't work exactly like that, you should still get the idea!