sql server(根据条件查找表的数量)

时间:2013-01-14 17:29:29

标签: sql sql-server-2008

我有一个如下表

RequestNo  Facility  status 
1           BDC1      Active
1           BDC2      Active
1           BDC3      Active
2           BDC1      Active
2           BDC2      Active 

我想要这样

RequestNo  Facilty       Count 
1          BDC (1,2,3)   1
2          BDC(1,2)      1

计数应基于具有facilty的状态显示.Fcilityv应仅作为BDC

2 个答案:

答案 0 :(得分:0)

试试这个,(假设您的设施是固定的4个字符代码)

SELECT RequestNo, Fname + '(' + FnoList + ')' Facilty, count(*) cnt
FROM 
(
    SELECT  distinct RequestNo, 
    SUBSTRING(Facility,1,3) Fname,
    stuff((
        select ',' + SUBSTRING(Facility,4,4)
        from Dummy
        where RequestNo = A.RequestNo AND
        SUBSTRING(Facility,1,3) = SUBSTRING(A.Facility,1,3)
        for xml path('')
            ) ,
         1, 1, '') as FnoList
    FROM Dummy A
) x
group by RequestNo, Fname, FnoList;

SQL DEMO

答案 1 :(得分:0)

这不会对Facility字段的长度产生任何限制。它从开头剥离出字符,从结尾处删除数字:

SELECT RequestNo, FacNameNumbers, COUNT(Status) as StatusCount
FROM
(
SELECT DISTINCT
  t1.RequestNo, 
  t1.Status,
  substring(facility, 1, patindex('%[^a-zA-Z ]%',facility) - 1) + 
  '(' +
    STUFF((
      SELECT DISTINCT ', ' + t2.fac_number  
      FROM (
        select distinct 
          requestno, 
          substring(facility, 2 + len(facility) - patindex('%[^0-9 ]%',reverse(facility)), 9999) as fac_number
        from facility    
    ) t2
    WHERE t2.RequestNo = t1.RequestNo 
    FOR XML PATH (''))
  ,1,2,'') + ')' AS FacNameNumbers
FROM Facility t1
) final
GROUP BY RequestNo, FacNameNumbers

SQL Fiddle