0

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

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

我想要的摘要视图

世界观

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 |

欧洲、中东和非洲视图

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 查询来填充所有字段来做到这一点,但被告知可以通过在数据库中进行透视来完成,但不知道具体如何?

任何人都可以提供一些帮助吗?

4

1 回答 1

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]
于 2012-05-30T17:46:21.267 回答