0
我想要一個查詢透視一些數據,它工作正常,除了我發現我們的應用程序開發進一步下游的數據問題。我注意到的是,由於我需要最大化,因爲需要一個聚合函數的樞軸,它是字面上最大的價值,而不考慮列不明顯相同。我是新來的pivoting,所以我可能做錯了我想要的結果。任何幫助或方向將不勝感激。SQL Server:與分組樞軸
查詢:
SELECT
@cols = STUFF((SELECT ',' + QUOTENAME(proto_name)
FROM #temp_rackplan
GROUP BY proto_name
ORDER BY proto_name
FOR XML PATH(''),TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
SET @query = 'SELECT
dept_catg_grp_desc AS [Category Group]
,dept_category_desc AS [Category]
,fineline_desc AS [Fineline]
,Supplier
,ty_cust_choice_qty AS [CC]
,season_code AS [SC]
,set_strategy_desc AS [Set Strategy]
,ty_landed_cost_amt AS [Landed Cost]
,ty_freight_factor_pct AS [FF%]
,ty_cost_w_ff AS [Cost w/FF]
,ty_retail_amt AS [Retail $]
,mu_pct AS [MU%]
,in_store_wm_yr_wk_id AS [In Str Wk]
,ty_start_wm_yr_wk_id AS [Start Wk]
,ty_end_wm_yr_wk_id AS [End Wk]
,ty_md_wm_yr_wk_id AS [MD Wk]
,fixture_group_desc AS [Fixture]
,Brand
,' + @cols +
'
FROM
(
SELECT
dept_catg_grp_desc
,dept_category_desc
,fineline_desc
,Supplier
,ty_cust_choice_qty
,season_code
,set_strategy_desc
,ty_landed_cost_amt
,ty_freight_factor_pct
,ty_cost_w_ff
,ty_retail_amt
,mu_pct
,in_store_wm_yr_wk_id
,ty_start_wm_yr_wk_id
,ty_end_wm_yr_wk_id
,ty_md_wm_yr_wk_id
,fixture_group_desc
,Brand
,proto_name
,trgt_rack_cnt
FROM
#temp_rackplan
) AS x
PIVOT
(
MAX(trgt_rack_cnt)
FOR proto_name in (' + @cols + ')
) AS p '
查詢結果:
Catgrp Category Fineline Set Strategy Fixture Proto A Proto B Proto C
----------------------------------------------------------------------------
SHOES MENS 254 10-50 4WAY 2 1 1
SHOES MENS 254 10-50 H-RACK 2 1 1
SHOES MENS 254 60-90 4WAY 2 1 1
SHOES MENS 254 60-90 H-RACK 2 1 1
SHOES MENS 2920 10-50 4WAY 2 1 1
SHOES MENS 2920 10-50 H-RACK 2 1 1
SHOES MENS 2920 60-90 4WAY 2 1 1
SHOES MENS 2920 60-90 H-RACK 2 1 1
期望的結果(匹配數據庫):
Catgrp Category Fineline Set Strategy Fixture Proto A Proto B Proto C
----------------------------------------------------------------------------
SHOES MENS 254 10-50 4WAY 2 1 1
SHOES MENS 254 10-50 H-RACK 1 1 1
SHOES MENS 254 60-90 4WAY 1 1 1
SHOES MENS 254 60-90 H-RACK 1 1 1
SHOES MENS 2920 10-50 4WAY 1 1 1
SHOES MENS 2920 10-50 H-RACK 1 1 1
SHOES MENS 2920 60-90 4WAY 2 1 1
SHOES MENS 2920 60-90 H-RACK 1 1 1