【问题标题】:PIVOT ouput in stored procedure in sql server 2008 [duplicate]sql server 2008中存储过程中的PIVOT输出[重复]
【发布时间】:2011-12-22 11:48:59
【问题描述】:

可能重复:
dynamic sql pivot in sql server

如何更改 PIVOT 输出的存储过程

SELECT COUNT(Rly) AS TheCount, Rly FROM  SPAD 

WHERE  Rly IN ('CR', 'ER', 'ECR', 'ECoR', 'NR', 'NCR', 'SR', 'SCR', 'SER', 'SECR', 'WR', 'WCR', 'Kolkata') 


GROUP BY Rly

【问题讨论】:

  • 您是否要针对 rly 的每个值进行旋转并将 count 显示为其值? rly 的值是否会超过您列出的值?
  • 需要更多关于期望结果的细节,所以我们不必猜测。你自己也试过吗?有很多PIVOT例子in BOL

标签: sql-server-2008 stored-procedures


【解决方案1】:

这假设您有有限数量的 rlys 值;当前实现此目的的唯一其他方法是在有更多值时使用 DYNAMIC SQL。 (搜索link

Select
sum(case when rly = 'CR' then 1 else 0 end) as "CR",
sum(case when rly = 'ER' then 1 else 0 end) as "ER",
sum(case when rly = 'ECR' then 1 else 0 end) as "ECR",
sum(case when rly = 'ECoR' then 1 else 0 end) as "ECoR",
sum(case when rly = 'NR' then 1 else 0 end) as "NR",
sum(case when rly = 'NCR' then 1 else 0 end) as "NCR",
sum(case when rly = 'SR' then 1 else 0 end) as "SR",
sum(case when rly = 'SCR' then 1 else 0 end) as "SCR",
sum(case when rly = 'SER' then 1 else 0 end) as "SER",
sum(case when rly = 'SECR' then 1 else 0 end) as "SECR",
sum(case when rly = 'WR' then 1 else 0 end) as "WR",
sum(case when rly = 'WCR' then 1 else 0 end) as "WCR",
sum(case when rly = 'Kolkata' then 1 else 0 end) as "Kolkata"
FROM SPAD

EDITED 接受后从计数变为总和。

【讨论】:

  • 先生,两种解决方案都有效,但总没有。每个 Rly 下的 Rly,例如 CR 38、ER 38、ECR 38。请帮助。
  • 非常感谢。解决方案使用 SUM 代替计数按需要工作。
  • 请记住,如果您的 rly 有 MORE 或值,这将不起作用。在这种情况下,只有 DYNAMIC SQL 可以帮助您。
  • 再次感谢您的宝贵意见,先生。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-25
  • 1970-01-01
  • 2015-01-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多