如何将静态CrossTab SQL查询转换为动态?

时间:2016-07-12 20:42:58

标签: sql sql-server sql-server-2008 tsql sql-server-2012

我有以下CrossTab SQL查询&它的工作正常。但是,我有限制硬编码100商店否,如果插入新的StoreNo,我是否可以动态生成StoreNo。

下面是我的查询:

SELECT

T1.[Menu_Code] AS 'Menu Code',
T1.[Short_Menu_Name] AS 'Menu Name',
SUM(case when T2.Store_id=1 then  (T2.PMXUSO + T2.PMXUSG+ T2.PMXUSI+  T2.PMXUSD+  T2.PMXUPR+  T2.PMXUEM+  T2.PMXUMM) else 0 end) AS 'Store No: 1 | Units Sold',
SUM(case when T2.Store_id=1 then ( ( (T2.PMXUSO + T2.PMXUSI+ T2.PMXUSG+ T2.PMXUSD+ T2.PMXUPR+ T2.PMXUEM+ T2.PMXUMM) * (T2.PMXPOB ))+(T2.PMXUSG * T2.PMXPGN) ) else 0 end) AS 'Store No: 1 | Units Sale',

SUM(case when T2.Store_id=2 then  (T2.PMXUSO + T2.PMXUSG+ T2.PMXUSI+  T2.PMXUSD+  T2.PMXUPR+  T2.PMXUEM+  T2.PMXUMM) else 0 end) AS 'Store No: 2 | Units Sold',
SUM(case when T2.Store_id=2 then ( ( (T2.PMXUSO + T2.PMXUSI+ T2.PMXUSG+ T2.PMXUSD+ T2.PMXUPR+ T2.PMXUEM+ T2.PMXUMM) * (T2.PMXPOB ))+(T2.PMXUSG * T2.PMXPGN) ) else 0 end) AS 'Store No: 2 | Units Sale'

FROM  [Master_Menu_Items] T1 LEFT JOIN [Fact_Qtlysales_CSHPMXP0] T2 ON T1.Menu_code = T2.PMXMIC

WHERE T2.FCT_DATE_KEY=20160710 and T2.Store_id IN (1,2)

GROUP BY T1.[Menu_Code],
         T1.[Short_Menu_Name]

ORDER BY T1.[Menu_Code]

以上查询显示两个StoreID&我有大约100个,我需要动态地带它们。

0 个答案:

没有答案