gpt4 book ai didi

sql-server-2008-r2 - SQL Server 2008 中针对动态列的算术运算符

转载 作者:行者123 更新时间:2023-12-04 18:05:15 25 4
gpt4 key购买 nike

我有查询创建表和下面的结果:

-- tblPart PartCode[NVARCHAR(50)],UnitPrice[Decimal(18,2)]
SELECT * INTO #tblPart FROM(
SELECT 'A' PartCode, '10' UnitPrice
UNION All
SELECT 'B','11'
UNION All
SELECT 'C','38'
UNION All
SELECT 'D','20'
UNION All
SELECT 'E','12')part;

-- tblPartCondition ConditionCode[NVARCHAR(50)],PercentagePrice[Decimal(18,2)]
SELECT * INTO #tblPriceCondition FROM(
SELECT 'Weekly' ConditionCode, '3' PercentagePrice
UNION All
SELECT 'Urgent','-5'
UNION All
SELECT 'Hotline','-10'
UNION All
SELECT 'Normal','0')pricecondition


SELECT PartCode,
[Weekly]=p.UnitPrice + (SELECT (CAST(c.PercentagePrice AS DECIMAL(18,2))/100) FROM #tblPriceCondition c WHERE c.ConditionCode='Weekly'),
[Urgent]=p.UnitPrice + (SELECT (CAST(c.PercentagePrice AS DECIMAL(18,2))/100) FROM #tblPriceCondition c WHERE c.ConditionCode='Urgent'),
[Hotline]=p.UnitPrice + (SELECT (CAST(c.PercentagePrice AS DECIMAL(18,2))/100) FROM #tblPriceCondition c WHERE c.ConditionCode='Hotline'),
[Normal]=p.UnitPrice + (SELECT (CAST(c.PercentagePrice AS DECIMAL(18,2))/100) FROM #tblPriceCondition c WHERE c.ConditionCode='Normal')
FROM #tblPart p

DROP TABLE #tblPart
DROP TABLE #tblPriceCondition

结果如下:

PartCode    Weekly   Urgent   Hotline    Normal
........ ...... ...... ....... ......
A 10.03 9.95 9.9 10
B 11.03 10.95 10.9 11
C 38.03 37.95 37.9 38
D 20.03 19.95 19.9 20
E 12.03 11.95 11.9 12

上面的查询是基于#tblPartCondition 中的已知列,Pls。知道列是否未知吗? (例如,如果用户添加新的 PercentageCode、PercentagePrice)。感谢您宝贵的时间和分享。谢谢!

最佳答案

获取数据透视表的列

DECLARE @cols NVARCHAR (MAX)

SELECT @cols = COALESCE (@cols + ',[' + ConditionCode + ']', '[' + ConditionCode + ']')
FROM (SELECT DISTINCT ConditionCode FROM #tblPriceCondition) PV
ORDER BY ConditionCode

使用CROSS JOIN获取每个PartCodeConditionCodePercentagePrice

DECLARE @query NVARCHAR(MAX)
SET @query = 'SELECT PartCode,' + @cols + ' FROM
(
SELECT PARTCODE,ConditionCode,
CAST(UnitPrice + CAST(PercentagePrice AS DECIMAL(18,2))/100 AS DECIMAL(18,2)) VALUE
FROM #tblPart
CROSS JOIN #tblPriceCondition
) x
PIVOT
(
MIN(VALUE)
FOR ConditionCode IN (' + @cols + ')
) p
'

EXEC SP_EXECUTESQL @query

请回复如何处理负值。
会更新。

关于sql-server-2008-r2 - SQL Server 2008 中针对动态列的算术运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28290971/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com