t-sql pivot过滤器基于输入列名称

时间:2010-05-27 21:46:25

标签: sql sql-server tsql sql-server-2008

基于以下AreaState表

Area    State
-------------------
A1  Active
A1  Active
A1  Active
A1  Proposed
A1  Proposed
A2  Active
A2  Proposed

我想写一个存储过程,它返回每个区域的状态计数。存储过程的输入是任何有效状态(在这种情况下,@ state是输入参数)。我希望下面会有效,但事实并非如此。

declare @state varchar(10)
set @state = 'Active'

select Area, QUOTENAME(@state)
from
(
  select Area, State from AreaState
) as src
pivot
(
   count(State) for State in (QUOTENAME(@state))
) as pvt

PLS。建议。

2 个答案:

答案 0 :(得分:1)

我在等待反馈时可能会有错误的要求,但我认为您可以使用简单的GROUP BY查询。

<强>代码:

SELECT Area, State, Count(*) as 'Count'
FROM x
GROUP BY Area, State

测试案例

WITH x AS (
    SELECT 'A1' as Area, 'Active' as State
    UNION ALL
    SELECT 'A1' as Area, 'Active' as State
    UNION ALL
    SELECT 'A1' as Area, 'Active' as State
    UNION ALL
    SELECT 'A1' as Area, 'Proposed' as State
    UNION ALL
    SELECT 'A1' as Area, 'Proposed' as State
    UNION ALL
    SELECT 'A2' as Area, 'Active' as State
    UNION ALL
    SELECT 'A2' as Area, 'Proposed' as State
)
SELECT Area, State, Count(*) as 'Count'
FROM x
GROUP BY Area, State

<强>输出:

Area    State      Count
------------------------
A1      Active     3
A1      Proposed   2
A2      Active     1
A2      Proposed   1

答案 1 :(得分:0)

我不确定这是否是最佳方法,但确实解决了这个问题。

declare @state varchar(20)
set @state = 'Proposed'

create table #tt_Result
(
  Area varchar(max),
  [Active] int,
  [Proposed] int
)

insert into #tt_Result
select Area, [Active], [Proposed]
from
(
  select Area, State from AreaState
) as src
pivot
(
   count(State) for State in ([Active], [Proposed])
) as pvt

select Area, 
case
  when @state = 'Active' then [Active]
  when @state = 'Proposed' then [Proposed]
end as [Count]
from #tt_Result

drop table #tt_Result