我将一系列查询串联在一起,我将其作为单个查询或作为具有一个子查询的查询。 我需要显示具有特定状态的作业总数,这些作业按作业处于该状态的天数范围分组。
E.g。 (用于概念目的的随机数据)
fldFranchiseCode Status 0-9 10-19 20-29 etc
Franchise A Status1 1 0 3
Franchise A Status2 2 1 4
Franchise A Status4 3 2 1
Franchise B Status2 1 6 4
这是我到目前为止所做的,但我收到一个SQL错误 - 'pvt'附近的语法不正确。'
SELECT * FROM
(SELECT fldFranchiseCode, Range AS [Day Range], COUNT(*) AS Jobs
FROM (SELECT fldFranchiseCode, CASE WHEN Days BETWEEN 0 AND 9 THEN '0- 9'
WHEN Days BETWEEN 10 AND 19 THEN '10-19'
WHEN Days BETWEEN 20 AND 29 THEN '20-29'
WHEN Days BETWEEN 30 AND 39 THEN '30-39'
WHEN Days BETWEEN 40 AND 49 THEN '40-49'
WHEN Days BETWEEN 50 AND 59 THEN '50-59'
WHEN Days BETWEEN 60 AND 69 THEN '60-69'
WHEN Days BETWEEN 70 AND 79 THEN '70-79'
WHEN Days BETWEEN 80 AND 89 THEN '80-89'
WHEN Days BETWEEN 90 AND 99 THEN '90-99'
ELSE 'Over 100' END AS Range
FROM (SELECT fldRecordID,
T.fldInquiryRecordID,
fldDate,
NextDate,
DATEDIFF("D", fldDate, NextDate) AS Days,
fldStatus,
fldFranchiseCode
FROM ( SELECT fldRecordID,
T1.fldInquiryRecordID,
fldDate,
( SELECT MIN([fldDate])
FROM tblStatusLog T2
WHERE T2.[fldInquiryRecordID] = T1.[fldInquiryRecordID]
AND T2.[fldDate] > T1.[fldDate]
) AS NextDate,
fldStatus,
fldFranchiseCode
FROM tblStatusLog T1
JOIN tblInquiry ON T1.fldInquiryRecordID = tblInquiry.fldInquiryRecordID
) AS T
GROUP BY [Day Range],fldFranchiseCode) q1
pivot
(max(jobs)
FOR [Day Range] IN ([0- 9],[10-19],[20-29],[30-39],[40-49],[50-59],
[60-69],[70-79],[80-89],[90-99],[Over 100])
)as pvt
任何帮助非常感谢
答案 0 :(得分:1)
正确的缩进将有助于识别语法错误。 (好吧,或者首先避免嵌套查询四层深处。)
SELECT * FROM
(
SELECT fldFranchiseCode, ...
FROM
(
SELECT fldFranchiseCode, CASE ...
FROM
(
SELECT fldRecordID, ...
FROM
(
SELECT fldRecordID, ...
FROM tblStatusLog T1
JOIN tblInquiry ON T1.fldInquiryRecordID = tblInquiry.fldInquiryRecordID
) AS T
GROUP BY Range, fldFranchiseCode
^^^^^ note, can't group by an alias here
) q1
) AS q2 -- you need this one
) AS q3 -- and this one too
pivot
(
max(jobs)
FOR [Day Range] IN ([0- 9],[10-19],[20-29],[30-39],[40-49],[50-59],
[60-69],[70-79],[80-89],[90-99],[Over 100])
) as pvt;