我有(SQL管理工作室18)2019,我是一个SQL初学者,以下是我面临的问题:
1.如果我不能使用create,我就不能将结果保存为表,因为动态透视表必须声明NVARCHAR(MAX)而不是表。我不能将其声明为表,因为我不能编写动态代码来标识类型(我希望除BILL_ACCOUNT之外的每一列都是浮点型,它应该是NVARCHAR(50))。
1.即使当使用转换为NVARCHAR(MAX)它不工作的N '',它仍然返回问号在空单元格中这样替换(???????),如果我relace的空与英语它的工作,但在阿拉伯语它不.(这是回答的第二个字符串没有N之前,它只剩下1回答)
即使在SSIS中,它也不会阅读输出,而代码会在服务器上执行所需的输出(cell上的输出除外)。
DECLARE @BaseQuery TABLE (PORT_NAME NVARCHAR(50),BILL_ACCOUNT_NAME NVARCHAR(50), AVERAGE float);
INSERT INTO @BaseQuery SELECT
a.[PORT_NAME]PORT_NAME
,a.[BILL_ACCOUNT_NAME]
,SUM(a.[TOTAL_PRE_VAT_AMNT_PER_INVOICE])
/IIF((MAX(a.[YEAR])-MIN(a.[YEAR]))=0,1,(MAX(a.[YEAR])-MIN(a.[YEAR])))AVERAGE
from (
SELECT YEAR(r.[PAYMENT_DATE])YEAR
,r.[TOTAL_PRE_VAT_AMNT_PER_INVOICE]
,p.[PORT_NAME]
,ISNULL(m.[BILL_ACCOUNT_NAME_AR],N'غير معرف')BILL_ACCOUNT_NAME
FROM [DD_MART].[dbo].[DM_PORT_REVENUE] r
LEFT JOIN [DD_MART].[dbo].[DIM_PORT] p
on r.[PORT_ID]=p.[PORT_ID]
LEFT JOIN [DD_MART].[dbo].[DIM_BILL_MAIN_ACCOUNT] m
on r.[ACCOUNT_CODE]=m.[BILL_ACCOUNT_CODE]
)a
WHERE a.[YEAR] IN ((YEAR(SYSDATETIME())-1),(YEAR(SYSDATETIME())-2),(YEAR(SYSDATETIME())-3))
GROUP BY a.[PORT_NAME]
,a.[BILL_ACCOUNT_NAME];
DECLARE @Query NVARCHAR(MAX), @Columns NVARCHAR(MAX)
SELECT @Columns =
STRING_AGG(Product, ',')
FROM
(
SELECT DISTINCT
QUOTENAME(PORT_NAME) AS Product
FROM @BaseQuery
) AS D;
SET @Query =
N'SELECT
BILL_ACCOUNT_NAME, ' +@Columns + '
FROM
(
SELECT
a.[PORT_NAME]PORT_NAME
,a.[BILL_ACCOUNT_NAME]
,SUM(a.[TOTAL_PRE_VAT_AMNT_PER_INVOICE])
/IIF((MAX(a.[YEAR])-MIN(a.[YEAR]))=0,1,(MAX(a.[YEAR])-MIN(a.[YEAR])))AVERAGE
from (
SELECT YEAR(r.[PAYMENT_DATE])YEAR
,r.[TOTAL_PRE_VAT_AMNT_PER_INVOICE]
,p.[PORT_NAME]
,ISNULL(m.[BILL_ACCOUNT_NAME_AR],N''غير معرف'')BILL_ACCOUNT_NAME
FROM [DD_MART].[dbo].[DM_PORT_REVENUE] r
LEFT JOIN [DD_MART].[dbo].[DIM_PORT] p
on r.[PORT_ID]=p.[PORT_ID]
LEFT JOIN [DD_MART].[dbo].[DIM_BILL_MAIN_ACCOUNT] m
on r.[ACCOUNT_CODE]=m.[BILL_ACCOUNT_CODE]
)a
WHERE a.[YEAR] IN ((YEAR(SYSDATETIME())-1),(YEAR(SYSDATETIME())-2),(YEAR(SYSDATETIME())-3))
GROUP BY a.[PORT_NAME]
,a.[BILL_ACCOUNT_NAME]
) AS D
PIVOT
(
MAX(AVERAGE) FOR [PORT_NAME] IN (' + @Columns + ')
) AS P'
EXEC sp_executesql @Query;
1条答案
按热度按时间s3fp2yjn1#
使用临时表(#temp)代替表变量,它将正常工作。最后请保持习惯,删除临时表