Reputation: 61
I am trying to create a query that will output a count of a column and then list the names it counted:
Table 1: license_granted
users checkout
Bob 2014-11-18 01:00:00
Steve 2014-11-18 01:00:00
Bob 2014-11-18 01:30:00
Chris 2014-11-18 01:30:00
I am able to do my count and get this output:
checkout_time ctUsers
2014-11-18 01:00:00 2
2014-11-18 01:30:00 2
SELECT COUNT(DISTINCT users) AS ctUsers, checkout
FROM license_granted
GROUP BY checkout
What I would like to get is:
checkout_time ctUsers userlist
2014-11-18 01:00:00 2 Bob,Steve
2014-11-18 01:30:00 2 Bob,Chris
Can this be done in the query?
Thanks
UPDATE 11/20 Okay I dug a little further and found a solution that gives me the checkout time and the userlist. Now I am trying to figure out how to count the elements in the userlist:
SELECT a.ctDate, SUBSTRING(d.users,1, LEN(d.users) - 1) usersList, count(d.users) AS ctUsers
FROM (
SELECT DISTINCT convert(varchar(10), deniedTime, 126) AS ctDate
FROM hyperworks_checkouts
) a
CROSS APPLY
(
SELECT DISTINCT [username] + ', '
FROM hyperworks_checkouts AS B
WHERE A.ctdate = convert(varchar(10), deniedTime, 126)
FOR XML PATH('')
) d (users)
The output now looks like this:
ctDate usersList
2014-01-15 Bob
2014-01-16 Steve,Bob
2014-01-17 Mike,Chris,Jerry
If I try adding COUNT(d.users) in the Select I get a count of 1 each time because there is one list. How do I count the users in d.users?
Thanks
Upvotes: 5
Views: 15939
Reputation: 61
I found a solution. After looking at a few postings I was able to piece together the solution I needed:
SELECT a.ctDate, SUBSTRING(d.users,1, LEN(d.users) - 1) usersList,
(select len(d.users) - len(replace(d.users, ',', ''))) AS ctUsers
FROM (SELECT DISTINCT convert(varchar(10), deniedTime, 126) AS ctDate
FROM hyperworks_denials
) a
CROSS APPLY
(
SELECT DISTINCT [username] + ', '
FROM hyperworks_denials AS B
WHERE A.ctdate = convert(varchar(10), deniedTime, 126)
FOR XML PATH('')
) d (users)
Thanks everyone that gave suggestions
Upvotes: 1
Reputation: 1
Try following query
SELECT COUNT(DISTINCT users) AS ctUsers, checkout,to_char(wm_concat(users)) Name
FROM license_granted
GROUP BY checkout
Upvotes: 0
Reputation: 206
I think the GROUP_CONCAT function is what you are looking for.
So for your example, try:
SELECT COUNT(DISTINCT users) AS ctUsers, checkout, GROUP_CONCAT(DISTINCT users)
FROM license_granted
GROUP BY checkout
You can also define a custom separator for the GROUP_CONCAT
values by adding a SEPARATOR
clause inside the GROUP_CONCAT query, ie. GROUP_CONCAT(DISTINCT users SEPARATOR ' '
Upvotes: 2