我正在使用 MS Sql2008,
Table1: Plan.Plan
Table2: Plan.PlanFeature
Table3:Plan.PlanDetails
Plan.Plan
PlanID_PK PlanName AnnualPrice MonthlyPrice
1 Plan1 Free Free
2 Plan2 $50.00 $4.99
3 Plan3 $100.00 $9.99
Plan.PlanFeature
PlanFeatureID_PK FeatureName
- - - - - - - - - - - - - - - - - - - - - - - - - - -
1 Feature1
2 Feature2
3 Feature3
4 Feature4
Plan.PlanDetails
PlanDetailsID_PK PlanID_FK PlanFeatureID_FK Quantity Quantity_Type
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - - - - -
1 1 1 0 Included
2 1 2 0 Unlimited
3 1 3 2 None
4 1 4 0 Unlimited
5 2 1 0 Included
6 2 2 0 Unlimited
7 2 3 20 None
8 2 4 0 Unlimited
9 3 1 0 Included
10 3 2 0 Unlimited
11 3 3 >20 None
12 3 4 0 Unlimited
Output :
FeatureName Plan1 Plan2 Plan3
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Feature1 Included Included Included
Feature2 Unlimited Unlimited Unlimited
Feature3 2 20 >20
Feature4 Unlimited Unlimited Unlimited
AnnualPrice Free $50.00 $100.00
MonthlyPrice Free $4.99 $9.99
所以我们开始了,为了将行转换为列,我使用了 COALESCE 和 Pivot
这是我正在尝试的存储过程,
DECLARE @cols NVARCHAR(2000)
DECLARE @SubjectQuery NVARCHAR(MAX)
SELECT @cols = COALESCE(@cols + ',[' + PlanNames + ']',
'[' + PlanNames + ']')
FROM Plans.Plans
ORDER BY PlanNames
SET @SubjectQuery = 'SELECT FeatureName, ' + @cols + '
FROM
(select p.PlanId_PK, p.PlanNames,pf.FeatureName,pd.Quantity from Plans.PlanDetails pd
join Plans.Plans p on pd.PlanId_FK=p.PlanId_PK
join Plans.PlanFeatures pf on pd.PlanFeatureId_FK=pf.PlanFeatureId_PK ) S
PIVOT
(
Count(Quantity) --Dont know which aggregate functions i have to use here according to my output
FOR PlanNames IN
(' + @cols + ')) AS pvt'
exec @SubjectQuery
对于数量,我必须像这样检查条件MAX(CASE WHEN pd.Quantity = '0' THEN pd.Quantity_Type)as Quantity
,如果数量值为 0,那么我必须显示Quantity_type
值
在枢轴块内,根据我的输出不知道我必须使用哪个聚合函数,你能弄清楚这个吗?