透视数据以获得所需的结束视图

时间:2012-05-30 17:22:45

标签: sql sql-server pivot-table

我在数据库表中的数据......

SELECT [Quote Reference Number] 
      ,[Value]
      ,[Method]
      ,[Country]
      ,[SubRegion]
      ,[Route 1 or Route2]
      ,[TYPE A or B ]
  FROM Table 1 

我想要的摘要视图

WORLD VIEW

Subregion | Country | Count of Route1 + Type A quotes | Count of Route1 + Type B quotes|  Count of Route2 + Type A quotes | Count of Route2 + Type B quotes| All Routes & Types |

EMEA VIEW

Subregion | Country | Count of Route1 + Type A quotes | Count of Route1 + Type B quotes| Count of Route2 + Type A quotes | Count of Route2 + Type B quotes| All Routes & Types |

我可以通过创建一个包含2行的表并且只是执行大量的SQL查询来填充所有字段但是被告知它可以通过数据库中的透视来完成,但不知道具体怎么办?

有人可以提供一些帮助吗?

1 个答案:

答案 0 :(得分:1)

案例中的透视很难(但并非不可能),因为FOR... IN子句分别包含字段和一组值,而不是条件语句。你最好使用sum/case例如

SELECT 
      [Country]
      ,[SubRegion]
      ,SUM (CASE WHEN [Route 1 or Route2] = 'Route1' AND [TYPE A or B ] = 'A' 
             THEN 1 ELSE 0 END)
              as [Count of Route1 + Type A quotes ]
      ,SUM (CASE WHEN [Route 1 or Route2] = 'Route1' AND [TYPE A or B ] = 'B' 
             THEN 1 ELSE 0 END)
              as [Count of Route1 + Type B quotes ]
     ,SUM (CASE WHEN [Route 1 or Route2] = 'Route2' AND [TYPE A or B ] = 'A' 
             THEN 1 ELSE 0 END)
              as [Count of Route2 + Type A quotes ]
      ,SUM (CASE WHEN [Route 1 or Route2] = 'Route2' AND [TYPE A or B ] = 'B' 
             THEN 1 ELSE 0 END)
              as [Count of Route2 + Type B quotes]
      ,COUNT(*)  All Routes & Types
  FROM [Table 1]
  GROUP BY
       [Country]
      ,[SubRegion]