我正在使用动态数据透视查询来生成报告:
DECLARE @Columns VARCHAR(MAX)
DECLARE @Columns2 VARCHAR(MAX)
SET @Columns = ''
SET @Columns2 = ''
SELECT
@Columns = @Columns + (QUOTENAME(RTRIM(LTRIM(cast(datename(month, [dates]) as char(15))))+',' + RTRIM(LTRIM(cast(year([dates]) as char(20))))) + ',')
FROM
efoxsfc.dbo.FTX_FA_Calender
WHERE
1=1
AND CAST(dates AS DATETIME) >= DATEADD(mm, -5 ,DATEADD(m, DATEDIFF(m, 0,GETDATE()), 0))
AND dates <= DATEADD(m, DATEDIFF(m, 0,GETDATE()), 0)
SET @Columns = LEFT(@Columns, LEN(@Columns) - 1)
SELECT
@Columns2 = @Columns2 + 'ISNULL(' +(QUOTENAME(RTRIM(LTRIM(cast(datename(month, [dates]) as char(15))))+',' + RTRIM(LTRIM(cast(year([dates]) as char(20))))) + ',0)AS'+(QUOTENAME(RTRIM(LTRIM(cast(datename(month, [dates]) as char(15))))+',' + RTRIM(LTRIM(cast(year([dates]) as char(20))))) + ',') )
FROM
efoxsfc.dbo.FTX_FA_Calender
WHERE
1=1
AND CAST(dates AS DATETIME) >= DATEADD(mm, -5 ,DATEADD(m, DATEDIFF(m, 0,GETDATE()), 0))
AND dates <= DATEADD(m, DATEDIFF(m, 0,GETDATE()), 0)
SET @Columns2 = LEFT(@Columns2, LEN(@Columns2) - 1)
DECLARE @SQL NVARCHAR(MAX)
SET @SQL = ''
SET @SQL = 'WITH BaseData AS
(
select
vendor_code,
RTRIM(LTRIM(cast(datename(month, [CLOSED_DATE]) as char(15))))+'','' + RTRIM(LTRIM(cast(year([CLOSED_DATE]) as char(20)))) as [CLOSED_DATE],
count(vendor_code) as [No. of Case]
from #teamp t WITH (NOLOCK)
where
[CLOSED_DATE] is not null
group by
vendor_code, CLOSED_DATE
)
SELECT vendor_code,' + @Columns2 + 'FROM BaseData
PIVOT
(
sum([No. of Case])
FOR CLOSED_DATE IN (' + @Columns + ')
) AS PivotTable'
--Print @SQL
EXECUTE sp_executesql @SQL
现在我想在报告中添加供应商名称和供应商代码。供应商名称来自不同的表格
SELECT VendorName
FROM VENDOR_REQUIREMENT
WHERE vendorcode = 'ACEA'
请告诉我在哪里必须使用我的选择来获取vendorname!
提前致谢
答案 0 :(得分:0)
只需加入BaseData cte中的vendor_requirement表,然后选择需要它的vendorname。您还需要按照计数()
的新字段进行分组SET @SQL = 'WITH BaseData AS
(
select
t.vendor_code,
vr.vendorname,
RTRIM(LTRIM(cast(datename(month, [CLOSED_DATE]) as char(15))))+'','' + RTRIM(LTRIM(cast(year([CLOSED_DATE]) as char(20)))) as [CLOSED_DATE],
count(t.vendor_code) as [No. of Case]
from #teamp t WITH (NOLOCK)
join (select distinct vendorcode, vendorname from vendor_requirement) vr on t.vendor_code = vr.vendorcode
where
[CLOSED_DATE] is not null
group by
t.vendor_code, vr.vendorname, CLOSED_DATE
)
SELECT vendor_code,vendorname,' + @Columns2 + 'FROM BaseData
PIVOT
(
sum([No. of Case])
FOR CLOSED_DATE IN (' + @Columns + ')
) AS PivotTable'
--Print @SQL
EXECUTE sp_executesql @SQL
答案 1 :(得分:0)
不确定#temp表的来源。加入该表应该可以。
来自#temp t WITH(NOLOCK)INNER JOIN VENDOR_REQUIREMENT V ON T.vendor_code = V.vendor_code