简体   繁体   English

SQl交叉数据透视查询错误

[英]SQl cross pivot query error

Using SQL Server 2008 Management Studio: 使用SQL Server 2008 Management Studio:

I have the following cross tab query I'm currently creating, this is what I have so far. 我当前正在创建以下交叉表查询,这就是我到目前为止所拥有的。

CREATE TABLE #Months
(UserID int,
ModuleID int,
Passed bit,
Name nvarchar(255),
Company nvarchar(50),
LanguageID nvarchar(10),
CodeRegisteredWith nvarchar(50),
TotalLoggedInDuration int,
Region int,
IsAdmin bit,
IsRep bit,
IsRetailer bit,
IsTeamLeader bit,
dateregistered date,
total int,
usertotal int,
complete int,
January int, february int, march int, april int, may int, June int, July int,
August int, September int, October int, November int, December int)

SELECT
   [1] January,
   [2] February,
   [3] March,
   [4] April,
   [5] May,
   [6] June,
   [7] July,
   [8] August,
   [9] September,
   [10] October,
   [11] November,
   [12] December
   FROM
(
  SELECT DATEADD(MONTH,0,Convert(smalldatetime,[dateregistered],120))as months
  FROM #Temp WITH(NOLOCK)
) d
pivot 
(
   SUM(complete)
   for months in ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])
) p 

This query is meant to populate 12 new fields (months) with "passed" data: 该查询旨在使用“已通过”数据填充12个新字段(月):

So in theory you have 12 columns one record each cell will have a sum of how many users passed in that month. 因此,从理论上讲,您有12列,每条记录一个记录,每个单元格将具有该月通过的用户总数。

But I'm currently adding and testing as this is part of a massive stored procedure using virtual tables. 但是我目前正在添加和测试,因为这是使用虚拟表的大型存储过程的一部分。 when I run this procedure all the others work but this fails and complains: 当我运行此过程时,所有其他过程均正常工作,但失败并抱怨:

Msg 8114, Level 16, State 1, Procedure GRAPHMainQuery, Line 127 消息8114,级别16,状态1,过程GRAPHMainQuery,第127行
Error converting data type nvarchar to smalldatetime. 将数据类型nvarchar转换为smalldatetime时出错。
Msg 473, Level 16, State 1, Procedure GRAPHMainQuery, Line 127 消息473,级别16,状态1,过程GRAPHMainQuery,第127行
The incorrect value "1" is supplied in the PIVOT operator. PIVOT运算符中提供了不正确的值“ 1”。

Nvarchar to smalldatetime? Nvarchar到smalldatetime? I've already stored this as a date in my #table, I'm even using convert() I just don't understand why this is complaining? 我已经将其作为日期存储在#table中,甚至使用了convert(),我只是不明白为什么会抱怨?

Use 采用

MONTH(Convert(datetime,[dateregistered],120)) as months

to get the month number (returns an integer). 获取月份号(返回整数)。 DATEADD(...) returns a datetime/smalldatetime value, which can not be compared to the [1]...[12] DATEADD(...)返回datetime / smalldatetime值,该值不能与[1] ... [12]进行比较 month number columns in the PIVOT statement. PIVOT语句中的月份号列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM