-1

I want to pull users that only have ONE deviceID in a given month. Let's say I have the following table:

User    Device ID
Greg    1
Greg    2
Mike    3
Laura   4
Laura   5
Lisa    6
George  7
Peter   8
Paul    9
Paul    10
Jane    11

I only want to see Users who have ONLY one deviceID. so in this case Mike, Lisa, George, Peter and Jane. Is there a way to do this in SQL?

2
  • 2
    You'll wanna use HAVING Oct 24, 2018 at 21:23
  • thanks @sp_BlitzErik, what If I want to count the number of users with only one device ID? Im confused as to how to write that query. I am very new to SQL Oct 24, 2018 at 22:01

1 Answer 1

2

Expanding on Erik's comment.

Reference:

DROP TABLE IF EXISTS dbo.device
GO
CREATE TABLE dbo.device
 (
  userName nvarchar(128), 
  device_ID int
  );
GO
INSERT INTO dbo.device
  (userName, device_ID)
VALUES
  ('Greg', 1),
  ('Greg', 2),
  ('Mike', 3),
  ('Laura', 4),
  ('Laura', 5),
  ('Lisa', 6),
  ('George', 7),
  ('Peter', 8),
  ('Paul', 9),
  ('Paul', 10),
  ('Jane', 11);
GO

--uncomment the line with COUNT if you want to see the count of device
SELECT 
  userName
  --COUNT(device_id) AS numberOfDevice
FROM dbo.device
GROUP BY userName
HAVING COUNT(device_id)=1;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.