0

给定数据看起来像

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 个表,它看起来像这样:

选择 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.SCH_OWN_Id = Policy.POL_OWN_Id AND School.SCH_DCSF = Policy.POL_DCSF 上的内部加入政策
内部加入 PolicyLine 上 Policy.POL_Id = PolicyLine.PLI_POL_Id
内部连接 ​​CoverOption ON PolicyLine.PLI_COP_Id = CoverOption.COP_Id
内部加入 CoverPremium ON CoverOption.COP_Id = CoverPremium.CPR_COP_Id AND Policy.POL_OWN_Id = CoverPremium.CPR_OWN_Id
右外连接 StaffCategory ON CoverOption.COP_SCA_Id = StaffCategory.SCA_
4

2 回答 2

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

于 2012-08-15T10:15:55.847 回答
0

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

SELECT *
FROM yourtable 
PIVOT 
(SUM(Premium) FOR sch_name in ([£10.00],[£11.00],[Heads, Deps],[Relief Bursar],[Teaching staff])) 
于 2012-08-15T08:27:16.133 回答