-1

样本数据

srNO  productname StartDate    AStartdate       pStartdate
1       new       11-11-2010    11-11-2010      11-11-2010
2       old       01-01-2011    11-11-2011      09-11-2010
3       medium    01-01-2012    01-01-2012      16-07-2012
4       out       01-08-2012    16-01-2012      16-07-2012

我的查询

ALTER PROCEDURE [dbo].[Status_yearly]
(@MID NVARCHAR(max))
AS
BEGIN

DECLARE @Years nvarchar(max)
SELECT @Years = Stuff((SELECT DISTINCT ',[' 
                                       + Cast(Year(u.StartDate) AS 
                                       NVARCHAR(4 
                                              )) 
                                       + ']' 
                       FROM   [products] u 
                       FOR xml path('')), 1, 1, '') 
DECLARE @date nvarchar(max)
SET @date =CONVERT(VARCHAR(10),GETDATE(),105)
-- SELECT @date
DECLARE @SQL nvarchar(max)
SELECT @SQL = '
select
    *
from (
    select
      ''Product'' AS Status,''total_product'' as [YEAR], 
      productname, year(u.StartDate) as [y]
    from products u  WHERE 
    MID ='''+@MID+''' 
    AND u.Flag <> 0 

  ) Data
PIVOT (
  COUNT(productname)
  FOR [y]
  IN (
    ' + @Years + '
  )
) PivotTable

UNION ALL 
select
    *
from (
    select ''Finished'' AS Finished,
      ''In Time'' as [YEAR], 
     Coalesce(COUNT(productsname),0) AS productsname, Coalesce(COUNT(year(u.StartDate)),0) as [y]
    from products u  WHERE  u.AStartdate IS NOT NULL 
    AND u.AStartdate = u.pStartdate
    AND MID ='''+@MID+''' 


  ) Data
PIVOT (
  COUNT(productsname)
  FOR [y]
  IN (
    ' + @Years + '
  )
) PivotTable

'
EXECUTE (@SQL)
END

这给了我结果

    状态年 2012
    产品总数_产品 4
    及时完成 0
 select ''Finished'' AS Finished,
      ''In Time'' as [YEAR], 
     Coalesce(COUNT(productsname),0) AS productname, Coalesce(COUNT(year(u.StartDate)),0) as [y]
    from products u  WHERE  u.AStartdate IS NOT NULL 
    AND u.AStartdate = u.pStartdate
    AND MID ='''+@MID+''' 

这给了我这样的结果

Finished   YEAR     productname  Y
FINISHED  In Time        1       1

单独它给我计数为 1,但在存储过程中执行时它给我 0。

那么如何在程序中实现这一点?请注意,有时“完成”块中可能没有任何结果集,这就是我使用的原因

Coalesce(COUNT(productsname),0) AS productname, Coalesce(COUNT(year(u.StartDate)),0) 

请建议..

数据库是 SQL Server

4

1 回答 1

0

除了您的示例数据缺少flagandmid列(我假设它在您的表中)这一事实之外,问题似乎是使用了错误的列名。

COUNT(productsname)应该是COUNT(productname)(删除s)。

于 2012-07-16T13:48:19.377 回答