MySQL Query Count two Fields - mysql

I have a database table (notes) that has three columns: id, ticket, and user.
I need to show how many notes were entered by each user as well as how many unique tickets those notes were added to (grouped by user). For example, John Doe entered 100 notes into 50 unique tickets and Jane Doe entered 70 notes into 65 unique tickets. I'm not interested in which tickets they were added to, just how many.
Here is what I have so far.
select count(id) count
from notes
group by user
Is it possible to grab the number of unique tickets in the same query?

Use distinct inside the count:
select
user,
count(id) note_count,
count(distinct ticket) ticket_count
from notes
group by user

You are probably new to SQL. The query is something like:
select user, count(distinct TicketId) as NumTickets, count(id) as NumNotes
from notes
group by user
You should include the user in the select clause, so you know to whom the numbers apply. When naming things, it is a good idea to avoid reserved words like count, so I named on NumTickets and the other NumNotes.

Related

How to count in a SQL list

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;

Pulling different records from multiple tables as one transaction history list

I am working on an employee management/reward system and need to be able to show a single "transaction history" page that shows in chronological order the different events that the employee has experienced in one list. (Sort of like how in facebook you can goto your history/action section and see a chronological list of all the stuff that you have done and affects you, even though they are unrelated to eachother and just have you as a common user)
I have different tables for the different events, each table has an employee_id key and an "occured" timestamp, some table examples:
bonuses
customers
raise
complaints
feedback
So whenever an event occurs (ie a new customer is assigned to the employee, or the employee gets a complaint or raise) a new row is added to the appropriate table with the employee ID it affects and a timestamp of when it occured.
I need a single query to pull all records (upto 50 for example) that include the employee and return a history view of that employee. The field names are different in each table (ie the bonus includes an amount with a note, the customer includes customer info etc).
I need the output to be a summary view using column names such as:
event_type = (new customer, bonus, feedback etc)
date
title (a brief worded title of the type of event, specified in sql based on the table its referencing)
description (verbiage about the action, such as if its event_type bonus display the bonus amount here, if its a complain show the first 50 characters of the complaint message or the ID of the user that filed the complaint from the complaints table. All done in SQL using if statements and building the value of this field output based on which table it comes from. Such as if its from the customers table IF current_table=customers description='A customer was assigned to you by'.customers.assigner_id).
Ideally,
Is there any way to do this?
Another option I have considered, is I could do 5-6 different queries pulling the records each from their own table, then use a mysql command to "mesh/interleave" the results from all the queries into one list by chronological order. That would be acceptable too
You could use a UNION query to merge all the information together and use the ORDER BY clause to order the actions chronologically. Each query must have the same number of fields. Your ORDER BY clause should be last.
The examples below assume you have a field called customer_name in the customers table and bonus_amount in the bonuses table.
It would look something like this:
SELECT 'New Customer' as event_type, date,
'New customer was assigned' as title,
CONCAT('New Customer: ', customer_name, ' was assigned') as description
FROM customers
WHERE employee_id = 1
UNION
SELECT 'Bonus' as event_type, date,
'Received a bonue' as title,
CONCAT('Received a bonus of $', FORMAT(bonus_amount, 2), '.') as description
FROM bonuses
WHERE employee_id = 1
UNION
...
ORDER BY date DESC;

Find the one-time users in a system- sql table

I have a table with 6 columns- Date, time, action, user_id, channel, and time_and_date.
Action refers to open or close, when a user starts or end watching a tv channel.
My tasks are as following
to get an overview of the data:
- find the one-time users (who used the service only once or in only one day and
never came back) for each channel, each genre, each community
Anoother table provides the user_id, genre(news, sport....)
How can I find the one time users for those requirements?
You can try something like
SELECT FROM first_table LEFT JOIN users ON first_table.user_id=users.id GROUP BY users.id HAVING COUNT(users.id)=1
You can join your genre table after for selecting over genre channels...
To get the one-time users:
select user_id ,min(channel) as channel, min(genre) as genre, min(community) as community
from action_table
group by user_id
having min(date) = max(date);
Note the having clause. This guarantees that a users has only one date (but not necessarily one record).
This returns one value for each of the three dimensions -- for a one-time user they are the same. For someone who visits multiple times in one day, it chooses one value.
Sounds something like this:
select user_id, count(*)
from action_table
where action = 'open'
group by user_id
having count(*) = 1
order by user_id

SQL Count and Group By issue

I have a table Mbr that contains 3 fields, GroupType, LeaderID, and MemberID. Basically, all the members in an organization are divided up into these groups, identified by their leader's unique ID (LeaderID). Each member record also has their own MemberID, and the leaders themselves have a unique MemberID as well. The GroupType just designates whether the group a member is in which is considered a Large, Small, or Individual group.
I need to find out how many groups of each GroupType contain a certain number of members.
For example:
How many Large groups contain 6 members, 7 members, 8 members, 9 and so on.
How many Small Groups contain 2 members, 3 members, 4 members and 5 members
How many Individual groups there are.
Is it possible make a query to get a Count of the unique MemberID's for each group, and then get a COUNT of how many LeaderID's have a certain number of members associated to them?
Note: Since you are not specifying which DBMS you are using, I tried to do a basic query. In SQLServer or Oracle this can be much more elegant.
I'm assuming that a given Member can be Leader leader of only one Group if that is correct,
Question #1:
SELECT GroupType, NumberOfMembers, COUNT(LeaderID) AS NumberOfGroups
FROM (
SELECT GroupType, LeaderID, COUNT(*) AS NumberOfMembers
FROM MyTable
GROUP BY GroupType, LeaderID
) AS InnerGrouping
GROUP BY GroupType, NumberOfMembers
ORDER BY GroupType, NumberOfMembers
Question #2:
SELECT UniqueMemberIDPerGroup, COUNT(LeaderID) AS NumberOfLeaderID
FROM (
SELECT LeaderID, COUNT(DISTINCT MemberID) AS UniqueMemberIDPerGroup
FROM MyTable
GROUP BY LeaderID
) AS InnerGrouping
GROUP BY UniqueMemberIDPerGroup
I'm sure you can write some complex query with several subqueries to create a query to give you what you want, but I personally like more straightforward methods. In this case, it would be using some temp tables to store intermediate values. I would first group by several columns (that you are going to use as criterias) with count being the value for the query. I would then store these into a temp table and finally create a query to utilize the temp table to give you the results that you are looking for.

Get count of mutually shared relations

Say I have three tables that look like:
users:
id
event_registration:
id
user_id
event_id
events:
id
A user registers for an event and this registration is recorded in event_registration.
Is there a way I can calculate the count of events that a given set of users mutually share in a single MySQL statement? I figured out how to do this for two users, but I'd like to refactor
it to support X number of users (including just one user).
try
select count(event_id) as events
from event_registration
where user_id in (1,2,3)
group by event_id
having count(distinct user_id) = 3
You have to adjust the number 3 in the having clause acourding to the number of user_ids you are using in your in clause.