sql-以下列格式显示记录表

时间:2011-04-26 07:06:06

标签: sql sql-server-2005

问题第1部分

我有一个Roles表,它指定了每个候选人的级别和状态。

name     id     status      level       location     country
==========================================================
RAJ      1      PENDING      MAJOR      BANGALORE     INDIA   
SAM      2      ACTIVE       LEAD       KOLKATA       INDIA
ANN      3      CLOSED       SENIOR     HYDERABAD     INDIA
BEN      4      APPROVED     MINOR      PUNE          INDIA
JACK     5      APPROVED     MINOR      PUNE          INDIA
REC      6      ACTIVE       LEAD       BANGALORE     INDIA
VESPER   7      ACTIVE       LEAD       BANGALORE     INDIA
KISHOR   8      ACTIVE       LEAD       HYDERABAD     INDIA

我需要为每个级别的候选人数量生成一份报告,以及有多少人参加 基于所选位置和国家/地区的特定状态。我可能无法解释清楚。但我希望下面的图片可以帮助你帮助我。

status     MINOR   MAJOR   LEAD   SENIOR   Total 
==========================================================
PENDING    0       1       0      0        1
ACTIVE     0       0       4      0        4
CLOSED     0       0       0      1        1  
APPROVED   2       0       0      0        2

问题第2部分

如何重命名执行上述查询后显示的状态列中的值。假设我想将状态显示为“延迟响应”,将活动显示为“在线”。

4 个答案:

答案 0 :(得分:1)

;WITH PivotSource AS
(
SELECT id,status,LEVEL
FROM Roles
)
SELECT status,
       MINOR,
       MAJOR,
       LEAD,
       SENIOR,
       MINOR+MAJOR+LEAD+SENIOR AS Total
FROM PivotSource
PIVOT (COUNT(id) FOR LEVEL IN (MINOR,MAJOR,LEAD,SENIOR) ) AS Pvt;

答案 1 :(得分:1)

无PIVOT解决方案:

SELECT
  status,
  MINOR  = COUNT(CASE level WHEN 'MINOR'  THEN 1 END),
  MAJOR  = COUNT(CASE level WHEN 'MAJOR'  THEN 1 END),
  LEAD   = COUNT(CASE level WHEN 'LEAD'   THEN 1 END),
  SENIOR = COUNT(CASE level WHEN 'SENIOR' THEN 1 END),
  Total  = COUNT(*)
FROM Roles
GROUP BY status

答案 2 :(得分:0)

您需要使用数据透视表。这是一个例子:

http://blog.sqlauthority.com/2008/06/07/sql-server-pivot-and-unpivot-table-examples/

答案 3 :(得分:0)

关于第2部分的问题:

WITH PivotSource AS ( SELECT id,status,LEVEL FROM Roles ) SELECT 
Status= case Status when 'Pending' then 'Delayed Response'
        when 'Active' then 'online'  
         else 'unknown' End,
MINOR,MAJOR,LEAD, SENIOR,MINOR+MAJOR+LEAD+SENIOR AS Total
FROM PivotSource
PIVOT (COUNT(id) FOR LEVEL IN (MINOR,MAJOR,LEAD,SENIOR) ) AS Pvt;