SQL将字段转换为列

时间:2014-06-19 23:13:53

标签: sql sql-server transpose

在使用PIVOT和UNPIVOT的所有SQL转置问题中,我还没有看到将一行转置为列的问题。这是我的问题:

SELECT '' as Status, '' as "Count", sum(Created) as "Created", 
sum(Forwarded) as "Forwarded", sum(Replied) as "Replied"
FROM 
   (
      SELECT 
      CASE WHEN a.TO_WG_ID is null and a.CREATED_DATE_TIME =                          
         (select min(b.created_date_time) from ymtn.message b 
         where b.thread_id = a.thread_id) THEN 1 ELSE 0
       END AS "Created",
       CASE WHEN a.TO_WG_ID is not null and a.FROM_WG_ID is not null THEN 1 ELSE 0
       END AS "Forwarded",
       CASE WHEN a.TO_WG_ID is null and a.CREATED_DATE_TIME != (select 
         min(b.created_date_time) from ymtn.message b where b.thread_id =
         a.thread_id) THEN 1 ELSE 0
       END AS "Replied"
       FROM ymtn.MESSAGE a left join YMTN.WORKGROUP b
       ON a.FROM_WG_ID=b.WORKGROUP_ID where b.WORKGROUP_ID='1STOP_PROCESS' 
) a 

这是我从上面的查询输出的(有两个静态字段 - 状态和计数 - 如果我可以想出要正确转置它,我可能不需要):

Status    Count    Created    Forwarded    Replied
                     1693        209        1499 

这是我想要的输出:

Status    Count
Created   1693
Forwarded  209
Replied   1499

请帮我找到办法。谢谢!

3 个答案:

答案 0 :(得分:1)

测试数据

DECLARE @TABLE TABLE
 (  [Status] VARCHAR(10)
    ,[Count] VARCHAR(10)
    ,Created INT
    ,Forwarded INT
    ,Replied INT
  )
INSERT INTO @TABLE VALUES
('', '', 1693 , 209 ,1499)

查询

 ;WITH CTE
 AS
  (
   SELECT * FROM (
      SELECT Created, Forwarded, Replied FROM @TABLE  --<-- Your Existing query here
    ) t
   UNPIVOT (Vals FOR N IN (Created, Forwarded, Replied)) up
  )
SELECT N AS [Status] 
      ,Vals AS [Count]
 FROM CTE

结果集

╔═══════════╦═══════╗
║  Status   ║ Count ║
╠═══════════╬═══════╣
║ Created   ║  1693 ║
║ Forwarded ║   209 ║
║ Replied   ║  1499 ║
╚═══════════╩═══════╝

答案 1 :(得分:0)

你可以结合他们。

Select 'Created' as Status, Sum... as Count
from...
union all
select 'Forwarded', Som...
union all
select 'Replied, sum...

答案 2 :(得分:0)

是否需要进行复杂的转置?我想你可以用工会来给你你想要的东西。

  SELECT
    "Created" AS Status,
    COUNT(*) AS Count
  FROM ymtn.MESSAGE a
  LEFT JOIN YMTN.WORKGROUP b
    ON a.FROM_WG_ID = b.WORKGROUP_ID
  WHERE b.WORKGROUP_ID = '1STOP_PROCESS'
  AND a.TO_WG_ID IS NULL
  AND a.CREATED_DATE_TIME = (SELECT
    MIN(c.created_date_time)
  FROM ymtn.message c
  WHERE c.thread_id = a.thread_id)
  UNION
  SELECT
    "Forwarded",
    COUNT(*)
  FROM ymtn.MESSAGE a
  LEFT JOIN YMTN.WORKGROUP b
    ON a.FROM_WG_ID = b.WORKGROUP_ID
  WHERE b.WORKGROUP_ID = '1STOP_PROCESS'
  AND a.TO_WG_ID IS NOT NULL
  AND a.FROM_WG_ID IS NOT NULL
  UNION
  SELECT
    "Replied",
    COUNT(*)
  FROM ymtn.MESSAGE a
  LEFT JOIN YMTN.WORKGROUP b
    ON a.FROM_WG_ID = b.WORKGROUP_ID
  WHERE b.WORKGROUP_ID = '1STOP_PROCESS'
  AND a.TO_WG_ID IS NULL
  AND a.CREATED_DATE_TIME != (SELECT
    MIN(c.created_date_time)
  FROM ymtn.message c
  WHERE c.thread_id = a.thread_id)

(注意:没有提供样本表和数据,所以SQL不是测试执行的。)