-1

我有一张如下表

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

计数应基于带有设施的状态显示。Fcilityv 应仅作为 BDC

4

2 回答 2

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 小提琴

于 2013-01-14T18:06:43.643 回答
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 演示

于 2013-01-14T17:59:10.663 回答