SQL:服务器动态PIVOT查询

时间:2017-09-20 06:41:42

标签: sql-server tsql

我正在尝试使下面的Pivot SQL查询动态化。

应从以下查询中检索动态客户列表。

客户列表查询

SELECT
  Cust_Name
FROM dbo.Customer
INNER JOIN dbo.Service
  ON dbo.Customer.Cust_ID = dbo.Service.Cust_ID
WHERE [Next_Service] BETWEEN '2017-09-01' AND '2015-09-10'

透视查询

Select *
from
(
  select Customer.Cust_Name,Agreementlist.ProductQty,Store.Product_Name as Refill
  from dbo.Agreement INNER JOIN  dbo.Agreementlist ON dbo.Agreement.Agreement_ID = dbo.Agreementlist.Agreement_ID  INNER JOIN  dbo.Customer
  ON dbo.Customer.Cust_ID = dbo.Agreement.Cust_ID INNER JOIN  Store on Store.Pro_ID = dbo.Agreementlist.ProID  where  CatID='2' and Agreement.Status='Approved'

) x
pivot
(
  sum(ProductQty)
  for Cust_Name in ("list of customers resulted from the first query")  
) p

2 个答案:

答案 0 :(得分:0)

我已经使用这个SQL脚本来创建动态数据透视表

create function dbo.chk_fnk (@OverNumber int,  @BowlerID int,  @InningsID int)
returns int
as
begin
return 
      case when
           exists (select * 
                   from dbo.OverDetails
                   where BowlerID = @BowlerID and abs(OverNumber - @OverNumber) = 1 and InningsID = @InningsID)
           then 1
           else 0
      end;  
end;
go

ALTER TABLE dbo.OverDetails ADD CONSTRAINT UniqueConsecutiveBowlerInOneInning 
  CHECK (dbo.chk_fnk(OverNumber,  BowlerID,  InningsID) = 0);

答案 1 :(得分:0)

您可以添加光标以循环客户并将其添加到变量中。这在这里有效。

  declare @gruppe nvarchar(max)
  declare @gruppeSql nvarchar(max)
  declare @SQL nvarchar(max)

  DECLARE myCustomers CURSOR FOR

  SELECT Cust_Name FROM dbo.Customer INNER JOIN dbo.Service
  ON dbo.Customer.Cust_ID = dbo.Service.Cust_ID
  WHERE [Next_Service] BETWEEN '2017-09-01' AND '2015-09-10' 

  set @gruppeSql = ''

  OPEN myCustomers
  FETCH NEXT FROM myCustomers INTO @gruppe
  IF (@@FETCH_STATUS>=0)
  BEGIN
  SET @gruppeSql = @gruppeSql +'[' +@gruppe+']'
  FETCH NEXT FROM myCustomers INTO @gruppe
  END
  WHILE (@@FETCH_STATUS<>-1)
  BEGIN
  IF (@@FETCH_STATUS<>-2)
  SET @gruppeSql = @gruppeSql  + ',[' +@gruppe+']'
  FETCH NEXT FROM myCustomers INTO @gruppe
  END
  CLOSE myCustomers
  DEALLOCATE myCustomers 

  SET @gruppeSql = replace(@gruppesql,'''','')

  --select @gruppeSql
  SET @SQL = '
  Select *
  from
  (
   select Customer.Cust_Name,Agreementlist.ProductQty,Store.Product_Name as 
   Refill
   from dbo.Agreement INNER JOIN  dbo.Agreementlist ON 
   dbo.Agreement.Agreement_ID = dbo.Agreementlist.Agreement_ID  INNER JOIN  
   dbo.Customer
   ON dbo.Customer.Cust_ID = dbo.Agreement.Cust_ID INNER JOIN  Store on 
   Store.Pro_ID = dbo.Agreementlist.ProID  where  CatID=''2'' and 
   Agreement.Status=''Approved''

  ) x
  pivot
  (
     sum(ProductQty)
     for Cust_Name in ('+@gruppesql+')  
  ) p'

  print @sql
  exec(@sql)

SQL Print enter image description here

<强>结果: enter image description here