我有一个SQL Server数据库,我正在尝试提取特定数据。我需要计算每行中所有非空列的计数,从一列中减去另一列,以及来自其他表列(连接(的数据。
这就是我所在的地方,有人可以看看代码并告诉我我做错了什么(忽略硬编码日期,它们仅用于测试(?
SELECT
((CASE WHEN TC.Time0 IS NOT NULL THEN 1 ELSE 0 END)
+ (CASE WHEN TC.Time1 IS NOT NULL THEN 1 ELSE 0 END)
+ (CASE WHEN TC.Time2 IS NOT NULL THEN 1 ELSE 0 END)
+ (CASE WHEN TC.Time3 IS NOT NULL THEN 1 ELSE 0 END)
+ (CASE WHEN TC.Time4 IS NOT NULL THEN 1 ELSE 0 END)
+ (CASE WHEN TC.Time5 IS NOT NULL THEN 1 ELSE 0 END)
+ (CASE WHEN TC.Time6 IS NOT NULL THEN 1 ELSE 0 END)
+ (CASE WHEN TC.Time7 IS NOT NULL THEN 1 ELSE 0 END)
+ (CASE WHEN TC.Time8 IS NOT NULL THEN 1 ELSE 0 END)
+ (CASE WHEN TC.Time9 IS NOT NULL THEN 1 ELSE 0 END)) AS [Time Punches]
,SUM(CASE WHEN TC.Odometer0 IS NOT NULL THEN 1 ELSE 0 END) AS MileageStart
,SUM(CASE WHEN TC.Odometer1 IS NOT NULL THEN 1 ELSE 0 END) AS MileageEnd
,SUM(CASE WHEN MileageEnd >= 0 THEN 1 ELSE 0 END) -
SUM(CASE WHEN MileageStart < 0 THEN 1 ELSE 0 END) AS [Total Miles]
,D.DriverID AS [Driver ID]
,W.FirstName +' '+W.LastName AS [Driver Name]
,TC.PunchDate AS [DATE]
FROM tblTimeClock TC WITH (NOLOCK)
INNER JOIN tblDrivers D WITH (NOLOCK)
ON D.DriverID = TC.PunchID
INNER JOIN tblWorker W WITH (NOLOCK)
ON W.WorkerID = D.DriverID
WHERE TC.PunchID IS NOT NULL
AND TC.PunchDate BETWEEN '2017-05-01' AND '2017-06-01'
ORDER BY TC.PunchDate
有了上面,我得到这个错误:
>列 'tblTimeClock.Time0' 在选择列表中无效,因为它不包含在聚合函数或 GROUP BY 子句中。
但是我不知道如何将其包含在 GROUP BY 子句中 - 每次我尝试它都会导致弹出其他错误(不同,具体取决于我放置子句的位置(。
我问是否有人可以"告诉我我做错了什么"的原因是,一旦我修复了损坏的内容,我就不必为每个后续问题一次又一次地回来说"帮助"。我知道代码不好,这就是我需要帮助的原因。
我自己想通了:
SELECT
TC.PunchDate AS [Date]
,D.DriverID AS [Driver ID]
,W.FirstName +' '+W.LastName AS [Driver Name]
,((CASE WHEN TC.Time0 IS NOT NULL THEN 1 ELSE 0 END)
+ (CASE WHEN TC.Time1 IS NOT NULL THEN 1 ELSE 0 END)
+ (CASE WHEN TC.Time2 IS NOT NULL THEN 1 ELSE 0 END)
+ (CASE WHEN TC.Time3 IS NOT NULL THEN 1 ELSE 0 END)
+ (CASE WHEN TC.Time4 IS NOT NULL THEN 1 ELSE 0 END)
+ (CASE WHEN TC.Time5 IS NOT NULL THEN 1 ELSE 0 END)
+ (CASE WHEN TC.Time6 IS NOT NULL THEN 1 ELSE 0 END)
+ (CASE WHEN TC.Time7 IS NOT NULL THEN 1 ELSE 0 END)
+ (CASE WHEN TC.Time8 IS NOT NULL THEN 1 ELSE 0 END)
+ (CASE WHEN TC.Time9 IS NOT NULL THEN 1 ELSE 0 END)) AS [Time Punches]
,TC.Odometer0 AS [Starting Mileage]
,TC.Odometer1 AS [Ending Mileage]
,SUM(CASE WHEN TC.Odometer1 IS NOT NULL AND TC.Odometer1 >= 0 THEN TC.Odometer1 ELSE 0 END) -
SUM(CASE WHEN TC.Odometer0 IS NOT NULL AND TC.Odometer0 >= 0 THEN TC.Odometer0 ELSE 0 END) AS [Total Miles]
FROM tblTimeClock TC WITH (NOLOCK)
INNER JOIN tblDrivers D WITH (NOLOCK)
ON CAST(D.DriverID AS VARCHAR(50)) = TC.PunchID
INNER JOIN tblWorker W WITH (NOLOCK)
ON W.WorkerID = D.DriverID
WHERE TC.PunchID IS NOT NULL
AND TC.PunchDate BETWEEN @StartDate AND @EndDate
GROUP BY TC.Time0, TC.Time1, TC.Time2, TC.Time3, TC.Time4, TC.Time5, TC.Time6, TC.Time7, TC.Time8, TC.Time9, TC.Odometer0,TC.Odometer1, D.DriverID, W.FirstName, W.LastName, TC.PunchDate
ORDER BY TC.PunchDate