交叉表/交叉查询

时间:2012-08-15 07:59:45

标签: sql sql-server sql-server-2008 sql-server-2005

鉴于数据类似

PLI_ID   OWN_ID   DCSF_ID   SCH_NAME          PREMIUM1 PREMIUM2  DESCRIPTION  
901      2        1000     Dfe-School 1        86.40     7.20    Heads, Deps
902      2        1000     Dfe-School 2        403.30    8.40    Relief Bursar
903      2        1000     Dfe-School 3        327.00    8.40    £10.00 
904      2        1000     Dfe-School 4        381.50    8.40    £11.00 
905      2        1000     Dfe-School 5        152.60    8.40    Teaching staff

预期数据看起来像

School          £10.00  £11.00  Heads, Deps  Relief Bursar  Teaching staff  Total
Dfe-School 1                            
Dfe-School 2                            
Dfe-School 3                            
Dfe-School 4                            

Total                                                                  [Pre-Total]

我不确定是否按照建议编写Cross Tab或Cross Over查询。如果需要更多解释,请告诉我。

我的查询使用了大约6个表,它看起来像这样:

SELECT PolicyLine.PLI_POS_Id, Policy.POL_OWN_Id, Policy.POL_DCSF, School.SCH_Name, PolicyLine.PLI_Premium, CoverPremium.CPR_Premium, StaffCategory.SCA_Description FROM
School 
INNER JOIN Policy ON School.SCH_OWN_Id = Policy.POL_OWN_Id AND School.SCH_DCSF = Policy.POL_DCSF 
INNER JOIN PolicyLine ON Policy.POL_Id = PolicyLine.PLI_POL_Id 
INNER JOIN CoverOption ON PolicyLine.PLI_COP_Id = CoverOption.COP_Id 
INNER JOIN  CoverPremium ON CoverOption.COP_Id = CoverPremium.CPR_COP_Id AND Policy.POL_OWN_Id = CoverPremium.CPR_OWN_Id 
RIGHT OUTER JOIN StaffCategory ON CoverOption.COP_SCA_Id = StaffCategory.SCA_

2 个答案:

答案 0 :(得分:1)

根据您现有的查询,您可以使用以下内容:

SELECT School.SCH_Name school,
  [£10.00], [£11.00], 
  [Heads, Deps], [Relief Bursar], [Teaching staff]
FROM
(
  SELECT PolicyLine.PLI_POS_Id, 
    Policy.POL_OWN_Id, 
    Policy.POL_DCSF, 
    School.SCH_Name, 
    PolicyLine.PLI_Premium, 
    CoverPremium.CPR_Premium, 
    StaffCategory.SCA_Description 
  FROM School 
  INNER JOIN Policy 
    ON School.SCH_OWN_Id = Policy.POL_OWN_Id 
    AND School.SCH_DCSF = Policy.POL_DCSF 
  INNER JOIN PolicyLine 
    ON Policy.POL_Id = PolicyLine.PLI_POL_Id 
  INNER JOIN CoverOption 
    ON PolicyLine.PLI_COP_Id = CoverOption.COP_Id 
  INNER JOIN  CoverPremium 
    ON CoverOption.COP_Id = CoverPremium.CPR_COP_Id 
    AND Policy.POL_OWN_Id = CoverPremium.CPR_OWN_Id 
  RIGHT OUTER JOIN StaffCategory 
    ON CoverOption.COP_SCA_Id = StaffCategory.SCA_
) x
PIVOT
(
  sum(PLI_Premium)
  for SCA_Description in([£10.00], [£11.00], 
                     [Heads, Deps], [Relief Bursar], [Teaching staff])
) p

请参阅SQL Fiddle with Demo

答案 1 :(得分:0)

您可能想要PIVOT查询,但从您的示例中很难说出它应该是什么样的。

SELECT *
FROM yourtable 
PIVOT 
(SUM(Premium) FOR sch_name in ([£10.00],[£11.00],[Heads, Deps],[Relief Bursar],[Teaching staff]))