SQL计数列和列表值计数

时间:2014-11-19 22:01:32

标签: sql sql-server count

我正在尝试创建一个输出列数的查询,然后列出它计算的名称:

表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

我可以计算并获得此输出:

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 

我想得到的是:

checkout_time            ctUsers     userlist
2014-11-18 01:00:00         2        Bob,Steve
2014-11-18 01:30:00         2        Bob,Chris

可以在查询中完成吗?

由于

更新11/20好的我进一步挖了一下,找到了一个解决方案,给了我结账时间和用户列表。现在我想弄清楚如何计算用户列表中的元素:

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)

输出现在看起来像这样:

ctDate        usersList
2014-01-15    Bob
2014-01-16    Steve,Bob
2014-01-17    Mike,Chris,Jerry

如果我尝试在Select中添加COUNT(d.users),每次得到1的计数,因为有一个列表。如何统计d.users中的用户?

由于

3 个答案:

答案 0 :(得分:1)

我找到了解决方案。在看了几篇帖子后,我能够拼凑出我需要的解决方案:

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) 

感谢所有给出建议的人

答案 1 :(得分:0)

我认为GROUP_CONCAT功能正是您所需要的。

因此,对于您的示例,请尝试:

SELECT COUNT(DISTINCT users) AS ctUsers, checkout, GROUP_CONCAT(DISTINCT users)
FROM license_granted
GROUP BY checkout

您还可以通过在GROUP_CONCAT查询中添加GROUP_CONCAT子句来定义SEPARATOR值的自定义分隔符,即。 GROUP_CONCAT(DISTINCT users SEPARATOR ' '

答案 2 :(得分:0)

尝试以下查询

SELECT COUNT(DISTINCT users) AS ctUsers, checkout,to_char(wm_concat(users)) Name
FROM license_granted
GROUP BY checkout