SQL查询:客户名称,包括活动计数

时间:2017-12-15 18:50:06

标签: sql-server tsql count

这可能是一个非常简单的解决方案,我现在没有看到。

我需要一个SQL报告的脚本。我可以通过简单的SELECT获取所有客户名称:

SELECT
    t5.[Name] AS CustomerName
FROM
    [T5] t5
WHERE
    t5.Type IN (1, 2)
ORDER BY
    t5.[Name]

这为我提供了下拉菜单的有序列表,以选择客户名称。结果集如下所示:

CustomerName
------------
Customer 1 Name
Customer 2 Name
Customer 3 Name
...

但我不需要这个名字,我也需要在名称字符串中对该客户名称进行相关活动的次数。例如,对于该客户有38个活动,它应该如下所示:"(38)客户名称在这里"

该声明为我提供了一个特定客户的正确计数(在此示例中,"客户5名称")看起来像这样,它需要几个连接才能获得有:

SELECT
    COUNT(*)
FROM
    [T1] t1
INNER JOIN
    [T2] t2 ON t2.[ID] = t1.[Activity]
INNER JOIN
    [T3] t3 ON t3.[ID] = t2.[Username]
INNER JOIN
    [T4] t4 ON t4.[ID] = t3.[ID]
INNER JOIN
    [T5] t5 ON t5.[ID] = t4.[X]
WHERE
    t5.[Name] = 'Customer 5 Name'

现在显然我需要以某种方式组合这些,以获得以下结果集:

CustomerName
-------------------
(a) Customer 1 Name
(b) Customer 2 Name
(c) Customer 3 Name
(d) Customer 4 Name
(e) Customer 5 Name
(f) Customer 6 Name
...

(a-f是该客户的相应活动计数)

感谢您的帮助!

3 个答案:

答案 0 :(得分:0)

您应该使用group by

SELECT
    t5.[Name], COUNT(*)
FROM
    [T1] t1
INNER JOIN
    [T2] t2 ON t2.[ID] = t1.[Activity]
INNER JOIN
    [T3] t3 ON t3.[ID] = t2.[Username]
INNER JOIN
    [T4] t4 ON t4.[ID] = t3.[ID]
INNER JOIN
    [T5] t5 ON t5.[ID] = t4.[X]
group by t5.[Name]

答案 1 :(得分:0)

    WITH pre AS
    (
    SELECT  t5.[Name] AS CustomerName,  COUNT(*) AS ActivityCount
    FROM [T1] t1 
    INNER JOIN [T2] t2 ON t2.[ID] = t1.[Activity] 
    INNER JOIN [T3] t3 ON t3.[ID] = t2.[Username] 
    INNER JOIN [T4] t4 ON t4.[ID] = t3.[ID] 
    INNER JOIN [T5] t5 ON t5.[ID] = t4.[X] 
    WHERE t5.Type IN (1, 2) AND t5.[Name] = 'Customer 5 Name'
    GROUP BY t5.Name
    )

    SELECT '(' + ActivityCount + ') ' + CustomerName
    FROM pre

答案 2 :(得分:0)

我认为这会根据您的要求为您提供客户名称的编号。

  SELECT
         '(' + CAST(COUNT(*) AS nvarchar(4) ) + ') '  +    t5.[Name] as [CustomerName]
        FROM
            [T1] t1
        INNER JOIN
            [T2] t2 ON t2.[ID] = t1.[Activity]
        INNER JOIN
            [T3] t3 ON t3.[ID] = t2.[Username]
        INNER JOIN
            [T4] t4 ON t4.[ID] = t3.[ID]
        INNER JOIN
            [T5] t5 ON t5.[ID] = t4.[X]
        group by t5.[Name]