将2行组合到同一列

时间:2011-07-22 00:07:20

标签: sql sql-server-2008

嘿所以我现在的查询是

ALTER PROCEDURE [SSRS].[VolumeCustomers]
@UserID int
AS  

select 
    CaseTypeName,
    COUNT(CaseNo) as CaseCount,
    'Open' as indicator

FROM ORDERS.ApCase AC with (NOLOCK)
    join ORDERS.CaseType CT (NOLOCK) on CT.CaseTypeID = AC.CaseTypeID
    join WORKFLOW.WorkflowHistory WH (NOLOCK) on WH.EntityID = AC.CaseID and TableID = dbo.GetTableID('ApCase', 'ORDERS') and WH.Active = 1
    inner join WORKFLOW.WorkflowStep WS (NOLOCK) on WS.WorkflowStepID = WH.WorkflowStepID and WS.NextStepID is null
where (AC.Active =1 and AC.CreatedDate >= DATEADD(day,-7,getdate()) and AC.CreatedDate < GETDATE()) 
Group By CaseTypeName

union
select 
    CaseTypeName,
    COUNT(Caseno) as CaseCount,
    'Closed' as indicator

FROM ORDERS.ApCase AC with (NOLOCK)
    join ORDERS.CaseType CT (NOLOCK) on CT.CaseTypeID = AC.CaseTypeID
    join WORKFLOW.WorkflowHistory WH (NOLOCK) on WH.EntityID = AC.CaseID and TableID = dbo.GetTableID('ApCase', 'ORDERS') and WH.Active = 1
    join WORKFLOW.WorkflowStep WS (NOLOCK) on WS.WorkflowStepID = WH.WorkflowStepID and WS.NextStepID is not null
where (AC.Active =1 and AC.CreatedDate >= DATEADD(day,-7,getdate()) and AC.CreatedDate < GETDATE())  
GROUP BY CaseTypeName 
Order by CaseCount desc

和输出是

Cytogenetics    2   All
Cytogenetics    1   Open
Flow Tech   1   All
Flow Tech   1   Open
Surgical    1   All
Surgical             1  Open

但我希望细胞遗传学,流动技术和手术都出现在同一排 例如:

Cytogenetics    2   All 1   Open
Flow Tech            1        All      1    Open
Surgical             1  All      1        Open

如何编辑我的查询以反映这一点?

2 个答案:

答案 0 :(得分:1)

这有用吗?

SELECT A.*, B.CaseCount, B.indicator
  FROM (<First Part of Union in Question>) AS A INNER JOIN
       (<Second Part of Union in Question>) AS B ON A.CaseTypeName = B.CaseTypeName

答案 1 :(得分:0)

SELECT
    CaseTypeName,
    COUNT(CASE WHEN WS.NextStepID IS NULL     THEN Caseno END) AS CaseCountOpen,
    COUNT(CASE WHEN WS.NextStepID IS NOT NULL THEN Caseno END) AS CaseCountClosed,
    COUNT(CaseNo) AS CaseCountAll

FROM ORDERS.ApCase AC with (NOLOCK)
    JOIN ORDERS.CaseType CT (NOLOCK)
        ON  CT.CaseTypeID = AC.CaseTypeID
    JOIN WORKFLOW.WorkflowHistory WH (NOLOCK)
        ON  WH.EntityID = AC.CaseID
        AND TableID = dbo.GetTableID('ApCase', 'ORDERS')
        AND WH.Active = 1
    JOIN WORKFLOW.WorkflowStep WS (NOLOCK)
        ON  WS.WorkflowStepID = WH.WorkflowStepID
WHERE AC.Active = 1
  AND AC.CreatedDate >= DATEADD(day,-7,getdate())
  AND AC.CreatedDate < GETDATE()  
GROUP BY CaseTypeName 
ORDER BY CaseCountAll DESC