如何在SQL查询中使用distinct和count来计算多个列

时间:2016-03-06 14:24:41

标签: sql sql-server sql-server-2008 qsqlquery

MyTable的:

+-----------+-----------+---------+
| Cust_Name | Contract  | Status  |
+-----------+-----------+---------+
| ABC       | CISCO     | Active  |
| DEF       | Microsoft | Expired |
| ABC       | HP        | Expired |
| DEF       | DELL      | Active  |
| ABC       | CISCO     | Active  |
+-----------+-----------+---------+

MS SQL查询:

SELECT Cust_Name, Active_count,
       Contract = substring(List, 1, len(List) - 1)
FROM   (SELECT Cust_Name, COUNT(*) AS Active_count
        FROM  mytable
        WHERE status = 'Active'
        GROUP BY Cust_Name) AS a
CROSS  APPLY (SELECT    (SELECT Contract + ',  '
                 FROM   Mytable b
                 WHERE  b.Cust_Name = a.Cust_Name
                   AND  b.Status = 'Active'
                 FOR XML PATH(''), TYPE).value('.',  'nvarchar(MAX)')) AS b(List)

根据我的查询,我未能如下所示。我如何得到如下结果:

+-----------+--------------+--------------+
| Cust_Name | Active_count |  Contracts   |
+-----------+--------------+--------------+
| ABC       |            2 | CISCO,Oracle |
| DEF       |            1 | DELL         |
+-----------+--------------+--------------+

2 个答案:

答案 0 :(得分:0)

我会在最后使用STUFF()而不是SUBSTRING()来编写查询。无论如何,我认为你在子查询中只需要SELECT DISTINCT

SELECT a.Cust_Name, a.Active_count, Contract = b.List
FROM (SELECT Cust_Name, COUNT(DISTINCT Contract) AS Active_count
      FROM  mytable
      WHERE STS_CODE = 'Active'
      GROUP BY Cust_Name
     ) a CROSS  APPLY
     (SELECT STUFF((SELECT DISTINCT b.Contract + ',  '
                    FROM Mytable b
                    WHERE b.Cust_Name = a.Cust_Name AND  b.Status = 'Active'
                    FOR XML PATH(''), TYPE
                   ).value('.',  'nvarchar(MAX)'), 1, 2, ''
                  )
     ) AS b(List);

答案 1 :(得分:0)

请试试这个:

WITH CTE_Testtable AS (
 SELECT 
  Cust_Name,
  Contract,
  Status 
 FROM
  TESTTable
 WHERE
 Status = 'Active'
 GROUP BY 
 Cust_Name, Contract, Status
)
SELECT
 Cust_Name,
 COUNT(Cust_Name) Active_Count,
 STUFF((SELECT ', ' + Contract
  FROM 
   TESTTable B
  WHERE 
   B.Cust_Name = A.Cust_Name 
   AND Status = 'Active'
  GROUP BY Contract
  FOR XML PATH('')), 1, 2, '') 
FROM
 CTE_Testtable A
WHERE
 Status = 'Active'
GROUP BY 
 Cust_Name