我有一个SQL调用,它目前按年获取数据,并按照下面的代码逐月显示。
SELECT MaterialCode, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12]
FROM
(SELECT mb.MaterialCode, DATEPART(m, Date) as [dp], Weight
FROM Issues iss
JOIN MaterialBatches mb ON iss.MaterialBatchId = mb.Id
LEFT JOIN Materials m ON mb.MaterialCode = m.Code
WHERE IssueType = 'MaterialIssue' AND
DatePart(yyyy,Date) = 2013
AND Weight > 0
AND (COALESCE(m.IsNonDispenseMaterial,0) = 0 OR CAST((SELECT Value FROM ConfigurationSettings WHERE Name = 'IncludeNonDispenseWeights') as varchar(10)) = 'true')) i
PIVOT (SUM(Weight) FOR i.dp IN
( [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12] )) as pvt
此代码现在需要更改以使选定的起始月份可更改。使用下面的代码,我得到了948条记录\行。
SELECT Code, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12]
FROM
(SELECT mb.Code, DATEPART(m, Date) as [dp], Weight
FROM Issues iss
JOIN Batches mb ON iss.Id = mb.Id
LEFT JOIN Mats m ON mb.Code = m.Code
WHERE IssueType = 'MatIssue' AND
YEAR(Date) = 2013 AND MONTH(Date) = 01 OR
YEAR(Date) = 2013 AND MONTH(Date) = 02 OR
YEAR(Date) = 2013 AND MONTH(Date) = 03 OR
YEAR(Date) = 2013 AND MONTH(Date) = 04 OR
YEAR(Date) = 2013 AND MONTH(Date) = 05 OR
YEAR(Date) = 2013 AND MONTH(Date) = 06 OR
YEAR(Date) = 2013 AND MONTH(Date) = 07 OR
YEAR(Date) = 2013 AND MONTH(Date) = 08 OR
YEAR(Date) = 2013 AND MONTH(Date) = 09 OR
YEAR(Date) = 2013 AND MONTH(Date) = 10 OR
YEAR(Date) = 2013 AND MONTH(Date) = 11 OR
YEAR(Date) = 2013 AND MONTH(Date) = 12
AND Weight > 0
AND (COALESCE(m.IsNonDisp,0) = 0 OR CAST((SELECT Value FROM ConfigurationSettings WHERE Name = 'IncludeNonDisp') as varchar(10)) = 'true')) i
PIVOT(SUM(Weight) FOR i.dp IN
( [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12] )) as pvt
请告诉我,我哪里出错?
答案 0 :(得分:4)
看看这些鹦鹉,试试这个:
SELECT Code, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12]
FROM
(SELECT mb.Code, DATEPART(m, Date) as [dp], Weight
FROM Issues iss
JOIN Batches mb ON iss.Id = mb.Id
LEFT JOIN Mats m ON mb.Code = m.Code
WHERE IssueType = 'MatIssue'
AND YEAR(Date) = 2013
AND Weight > 0
AND (COALESCE(m.IsNonDisp,0) = 0 OR CAST((SELECT Value FROM ConfigurationSettings WHERE Name = 'IncludeNonDisp') as varchar(10)) = 'true')) i
PIVOT(SUM(Weight) FOR i.dp IN
( [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12] )) as pvt