Grouping other fields by common email - sql

I'd appreciate any assistance people could provide with this one. I've tried to follow a couple of other posts (GROUP BY to combine/concat a column), but when I do this, it combines everything.
I have a table in SQL that holds contact data. Some contacts in the database have the same email address, particularly admin#, accounts#, etc. We also have a list of contact preferences for each contact: Emergency Contact, Accounts, WHS, etc. I'm trying to select the results of the table, but only one row per email address.
My data looks like this:
However, I'd like it to group the rows together that have the same email address (I don't care about the names). I'd also like it to look at the contact preference fields and if even one of the joined fields had a yes, show a Y, otherwise show a N - see below example
As I mentioned, all my tests have been unsuccessful I'm afraid, so I would appreciate any assistance that you can provide.

You can use the following:
;WITH selected as (
select min(ContactID) as ContactID, Mail, max(EmergencyContact) as EmergencyContact,
max(AccountsCon) as AccountsCon, max(WHSContact) as WHSContact
from t
GROUP BY Mail
)
select t.ContactID, t.BusinessID, t.BusinessName, t. FirstName, t.LastName, t.Position, t.Mail, s.EmergencyContact, s.AccountsCon, s.WHSContact
from selected as s
inner join t as t ON t.ContactID = s.ContactID
This way you get the contactid, businessid, businessname, firstname, lastname and position from the first record found with each email and the last 3 columns you get using max (taking advantage that Y is greater than N, so if there is at least one Y it will get Y).

I think you can just use aggregation:
select businessid, businessname, max(firstname),
max(lastname), max(position),
email,
max(emergencycontact),
max(accountscor),
max(whcontact)
from t
group by businessid, businessname, email;

Related

using count and group by correctly

I have a relation CandyC(id, email, age, name, candy_id)
I want to count the CandyC.ids associated with a CandyC.candy_id once.
Attempt:
SELECT email, age, name
FROM CandyC
GROUP BY id
HAVING COUNT(DISTINCT candy_id) = 1;
It gives me an error:
not a group by expression
The group by clause need to have all the non aggregated columns selected directly. Also, it's usually a good idea to use having after the group by as it's the standard way of writing this (even though Oracle supports it the other way too).
Does this do what you want:
select email, age, name
from candyc
group by id, email, age, name
having count(distinct candy_id) = 1
If not, you should provide sample data and expected results in your question to clarify.
I think you want something more like this:
SELECT candy_id, COUNT(*)
FROM CandyC
GROUP BY candy_id;
I don't know what the email/age/name columns have to do with the question:
I want to count the CandyC.ids associated with a CandyC.candy_id once.

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 >=.

Selecting first unique email address in SQL

I have a list of UserIds (which is a uniqueidentifier), Names, email addresses and relationships.
Something like
SELECT UserId, Name, Email, Relationship FROM Users
Sample data would look like:
F87B7702-F0EE-11D3-B288-0000B4A488D3 Peter peter#peter.com Member
ZZZZZZZZ-F0EE-11D3-B288-0000B4A488D2 Joan peter#peter.com Principal
AAAAAAAA-F0EE-11D3-EEEE-0000B4A488D3 Bob bob#bob.com Principal
Relationship can be either be 'Principal' or 'Member', but a principal user can also be a member.
An email address isn't specific to a user (often a member user will have the same email address as a principal user).
I need to ensure that I only select 1 user per email address so that the same person won't be emailed twice. If there are 2 emails for the same user I need to select the principal record.
What's the easiest way to do this, bearing in mind that you can't do a max on a uniqueidentifier field? For the sample data I gave above I would need to return only the second and third record.
I was leaning towards ordering by Relationship, doing a group by and then max but I don't think that's possible.
Output required is UserId, Name, Email.
The ORDER BY in ROW_NUMBER() will allow you to choose how to prioritise your emails. Such as how to deal with an email with no Principle but multiple Members (maybe add , Name ASC so the member with the first alphabetically ordered name gets chosen?)
SELECT
*
FROM
(
SELECT
*,
ROW_NUMBER() OVER (PARTITION BY email ORDER BY Relationship DESC) AS sequence_id
FROM
yourTable
)
AS sequenced_table
WHERE
sequence_id = 1
I didn't quite understood you, but if you want to get email only once, preffering the principle user this code will do:
select UserId, Name, Email, Relationship
from Table
where Relationship='Principle' or ( Relationship='Member' and Email not in
(
select Email
from Table
where Relationship='Principle'
)
)
This will give you the second and third lines. If there are more conditions- expand your example.

how to use distinct in ms access

I have two tables. Task and Categories.
TaskID is not a primary key as there are duplicate values.When there are multiple contacts are selected for a specific task,taskid and other details will be duplicated.I wrote the query:
SELECT Priority, Subject, Status, DueDate, Completed, Category
FROM Task, Categories
WHERE Categories.CategoryID=Task.CategoryID;
Now as multiple contacts are selected for that task,for the taskid=T4, there are two records(highlighted with gray). I have tried using distinct in ms access 2003 but its not working. I want to display distinct records. (Here there's no requirement to show taskid) If I write :
select priority, distinct(subject), .......
and remaining same as mentioned in above query then its giving me an error. I have tried distinctrow also.But didnt get success. How to get distinct values in ms access?
Okay.Its working this way.
SELECT DISTINCT Task.Priority, Task.Subject, Task.Status, Task.DueDate,
Task.Completed, Categories.Category
FROM Task, Categories
WHERE (((Categories.CategoryID)=[Task].[CategoryID]));
I don't like using SELECT DISTINCT, I have found that it makes my code take longer to compile. The other way I do it is by using GROUP BY.
SELECT Priority, Subject, Status, DueDate, Completed, Category
FROM Task, Categories
WHERE Categories.CategoryID=Task.CategoryID
GROUP BY Subject;
I do not have VBA up at the moment but this should work as well.
Using SELECT DISTINCT will work for you, but a better solution here would be to change your database design.
Duplicate records may lead to inconsistent data. For example, imagine having two different status in different records with the same TaskID. Which one would be right?
A better design would include something like a Task table, a Contact table and an Assignment table, as follows (the fields in brackets are the PK):
Tasks: [TaskID], TaskPriority, Subject, Status, DueDate, Completed, StartDate, Owner, CategoryID, ContactID, ...
Contact: [ID], Name, Surname, Address, PhoneNumber, ...
Assignment: [TaskID, ContactID]
Then, you can retrieve the Tasks with a simple SELECT from the Tasks tables.
And whenever you need to know the contacts assigned to a Tasks, you would do so using the JOIN clause, like this
SELECT T.*, C.*
FROM TaskID as T
INNER JOIN Assignment as A
ON T.TaskID = A.TaskID
INNER JOIN Contac as C
ON A.ContactID = C.ID
Or similar. You can filter, sort or group the results using all of SQL's query power.

mysql query, two select

As soon as I apologize because I do not know or be able to explain exactly trouble.
How get value from table user_address.
how to pass user ID in the second "select".
select id, name, age,
(select address
from user_address
where user_id = ??user.id
ORDER BY address_name
LIMIT 1) AS address
from user
As an addendum to what already exists, you should probably not be relying on the specific order of rows in the database to give some sort of semantic meaning. If you have some better way of identifying which address you're after, you could use a join, such as:
select id, name, age, address
from user
inner join user_address
on user.id=user_address.user_id
where address_type='Home'
(adjust the where clause to whatever)
I assumed that you want to get something like the first address for a user
(each user may have a couple of addresses)
-there is another option that you want to find the first persone that lives in a given address (The solution below doesn't address this case)
SELECT u.id,u.name,u.age,a.ua as address
FROM
(
SELECT * FROM users
) u
INNER JOIN
(
SELECT userID, MIN(address) AS ua
FROM user_address
GROUP BY userID
) a
on u.id = a.userID
The syntax is for SQLServer - if you use MSAccess(you can use First and not min)
Hope it helps
Asaf