Get Groups of Customers Names based on their Title - sql

Get the Count of Contact's person by their title. (Table: Customers) below:
Now, below SQL code will get group counts, but I want to add also the names associated with each group if possible please:
SELECT ContactTitle, Count(ContactTitle) FROM Customers
GROUP BY ContactTitle;
Database: This is from NorthWind database.

You can use
SELECT ContactTitle, ContactName, Count(ContactTitle) over (partition by ContactTitle) as usersCoun FROM Customers;

Related

Selecting fields that are not in GROUP BY when nested SELECTS aren't allowed

I have the tables:
Product(code (PK), pname, (....), sid (FK)),
Supplier(sid(PK), sname, (....))
The assignment is:
Find Suppliers that supply only one product. Display their name (sname) and product name (pname).
It seem to me like a GROUP BY problem, so I used:
SELECT sid FROM
Product GROUP BY sid
HAVING CAST(COUNT(*) AS INTEGER) = 1;
This query have found me the list of sid's that supply one product only, but now I have encountered a problem:
The assignment forbids any form of nested SELECT queries.
The result of the query I have written has only one column. (The sid column)
Thus, I am unable to access the product name as it is not in the query result table, and if I would have added it to the GROUP BY statement, then the grouping will based on product name as well, which is an unwanted behavior.
How should I approach the problem, then?
Note: I use PostgreSQL
You can phrase the query as:
SELECT s.sid, s.sname, MAX(p.pname) as pname
FROM Product p JOIN
Supplier s
ON p.sid = s.sid
GROUP BY s.sid, s.sname
HAVING COUNT(*) = 1;
You don't need to convert COUNT(*) to an integer. It is already an integer.
You could put
max(pname)
in the SELECT list. That's an aggregate, so it would be fine.

JOIN multiple queries from same table into one result

I'm working on a question in a practical for university but can't figure out how to achieve the output I need. I am relatively new to SQL and am using Oracle 11g.
I have a single table called CUSTOMERS that I want to run three queries on to get the total count from each
CUSTOMERS (customer#, lastname, firstname, address, city, state, zip, referred, region)
The three queries on their own execute fine and produce the desired result but I need to find a way to combine them to produce a single result with three columns and the result of each query in each column.
SELECT COUNT(*) AS "Total Customers"
FROM CUSTOMERS;
SELECT COUNT(*) AS "Direct Customers"
FROM CUSTOMERS
WHERE referred IS NOT NULL;
SELECT COUNT(*) AS "Referred Customers"
FROM CUSTOMERS
WHERE referred IS NULL;
I have spent the last few hours reading here and other sites but just can't get my head around it. I suspect a JOIN or UNION may be required.
Use a single query with conditional aggregation:
SELECT
COUNT(*) AS "Total Customers",
COUNT(referred) AS "Direct Customers",
COUNT(CASE WHEN referred IS NULL THEN 1 END) AS "Referred Customers"
FROM CUSTOMERS;

Remove Duplicates from SQL Query

I am using this query currently to trigger a customer event. But sometimes the same customer will be in the results because they are assigned a different WorkOrderId, which is my primary filter. So, I want to expand the filter to also look for a unique CustomerName. In other words, if the query returns two rows with the same CustomerName then I want it to exclude the 2nd row altogether.
SELECT CustomerName, JobId, Email, CCEmail, WorkOrderId AS id
FROM dbo.vwWorkOrderDetail
WHERE JobStatusId=3 AND Active=1 AND LocationStopTypeId=1
ORDER BY WorkOrderId DESC
I've tried using DISTINCT but I continue to get results that include the same CustomerName in different rows. How can I setup this query so it returns results that passed all of the WHERE conditions and then only shows rows with a unique CustomerName?
As long as you include WorkOrderId, DISTINCT will do nothing for you. DISTINCT can only eliminate duplicates where all of the columns specified in the SELECT contain the same information. So to use DISTINCT to eliminate duplicate customers, you would need to do this:
SELECT DISTINCT CustomerName, JobId, Email, CCEmail
FROM dbo.vwWorkOrderDetail
WHERE JobStatusId=3 AND Active=1 AND LocationStopTypeId=1
ORDER BY WorkOrderId DESC
The best way to approach this to preserve a WorkOrderId is to make a new view based on the underlying tables. You will need to decide what WorkOrderId of the available WorkOrderIds you want to present. Typically this is the highest ID. If all you need is the WorkOrderId itself and not the details, this is actually pretty simple. Note the code below is a naïve example that assumes CustomerId is tied directly to a work order. To really answer this properly you'd need to provide the code for vwWorkOrderDetail.
SELECT CustomerName, JobId, Email, CCEmail, (SELECT MAX(WorkOrderId) FROM WorkOrders WHERE CustomerID = Customers.CustomerID) AS WorkOrderID
FROM Customers
WHERE JobStatusId=3 AND Active=1 AND LocationStopTypeId=1
ORDER BY WorkOrderId DESC
SELECT CustomerName, JobId, Email, CCEmail, max(WorkOrderId) AS id
FROM dbo.vwWorkOrderDetail
WHERE JobStatusId=3 AND Active=1 AND LocationStopTypeId=1
GROUP BY CustomerName, JobId, Email, CCEmail

ORDER BY + IN statement?

The marketing department wants to focus on the customers from Noth America first. Get the ID, last name and country of all customers. Build the list by bringing up the customers living in Canada and in the USA first, and finally order them by ID. Tip: use the IN expression in the ORDER BY clause.
I've tried many times
SELECT CustomerID, LastName, Country
FROM Customer
ORDER BY Country IN ('Canada', 'USA'), CustomerID
but it doesn't seem to work, as it takes the specified fields from all customers in the order they appear in the original table (which is also ordered by ID), even if I remove CustomerID from the ORDER BY clause, whithout caring to which country they belong to.
What should I do? I'm really new to SQL, and have no idea on how to fix this.
Edit: WHERE ins't suitable at all, as I need to take in consideration all customers, only making sure the Canadian and American ones appear at the top of the list.
Also I'm unsure statements like UNION, AS, EXCEPT and things like that are meant to be used, because the tutorial didn't go that deep already.
Not every DBMS has a boolean datatype. So the result of
Country IN ('Canada', 'USA'),
which is a boolean, can not be sorted in these DBMS.
You can use a CASE expression, however, to assign a value:
SELECT CustomerID, LastName, Country
FROM Customer
ORDER BY CASE WHEN Country IN ('Canada', 'USA') THEN 1 ELSE 2 END, CustomerID;
SELECT CustomerID, LastName, Country
FROM Customer
ORDER BY Country IN ('Canada', 'USA') desc, CustomerID asc
IN expression don't return value so you can't sort
You can try:
SELECT CustomerID, LastName, Country
FROM Customer
WHERE Country='Canada'
UNION ALL
SELECT CustomerID, LastName, Country
FROM Customer
WHERE Country='USA'
ORDER BY CustomerID
Using ORDER BY with UNION, EXCEPT, and INTERSECT When a query uses the
UNION, EXCEPT, or INTERSECT operators, the ORDER BY clause must be
specified at the end of the statement and the results of the combined
queries are sorted. The following example returns all products that
are red or yellow and sorts this combined list by the column
ListPrice.
https://msdn.microsoft.com/en-us/library/ms188385.aspx#Union

sql query for the following statement?

My table 'Customer' contains customerid , firstname, lastname, company,city,state,country, email, invoicetotal
Question: For countries that have at least two customers using yahoo as email provider, display the name alongside the revenue
My solution:
select county,sum(invoiceTotal)from customer where email like '%yahoo%'
group by Country,Email having Count(Country)>2
I am unable to get proper result the no of rows displayed in my output are different from the number of rows in expected output,Can any1 tell me where have i gone wrong???
You are grouping by email as well - just group by Country and you should be fine
select
county,
sum(invoiceTotal)
from customer
where email like '%yahoo%'
group by Country
having Count(Country)>2
You can't group by email, since that's unique. Fortunately, you don't have to.
select
county,
sum(invoiceTotal)
from customer
where email like '%yahoo%'
group by Country
having Count(Country)>=2
Because the statement say at least then you need put >=.