我试图在一个SQL语句中做太多。我想在输出表的适当位置获得小计和总计。这是我的SQL;
SELECT Date, DOW, Week, Year, logdate, Month, monum, netID, Logins,
creds, newb, netCnt, TOD, netCnt, activity
FROM (SELECT logdate
,activity
,DATE( logdate ) AS Date
,DAYOFWEEK( logdate ) AS DOW
,WEEK( logdate,0 ) AS Week
,YEAR( logdate ) AS Year
,DATE_FORMAT( logdate, '%M' ) AS Month
,DATE_FORMAT( logdate, '%m' ) AS monum
,CONVERT( netID,UNSIGNED INTEGER ) AS netID
,COUNT( callsign ) AS Logins
,COUNT( IF(creds <> '',1,NULL) ) AS creds
,COUNT( IF(comments LIKE '%first log in%',1,NULL) ) AS newb
,count( DISTINCT netID ) AS netCnt
,SUM( DISTINCT netID) AS allCnt
,SEC_TO_TIME( SUM(timeonduty) ) AS TOD
FROM NetLog
WHERE netID <> 0
AND activity NOT LIKE '%TEST%'
AND netcall LIKE '%W0KCN%'
AND substr(logdate,1,4) = 2017
GROUP BY Month, netID WITH ROLLUP ) AS t
ORDER BY t.logdate , logins
您会注意到每个月都会正确订购,直到您到达10月份。总计在10月之前而不是在结束之前(12月之后)排序。这是我可以在SQL中控制的东西,还是应该在PHP中修复它?我如何在SQL中修复它?
答案 0 :(得分:0)
您的第二个字段logins
将仅在第一个排序列的相等值内进行相应排序。否则,在第一列上排序优先级。尝试交换logdate
和logins
,看看发生了什么。
答案 1 :(得分:0)
原来我需要一个CASE声明才能使其正常工作。
SELECT Date, DOW, Week, Year, Month, monum, netID, Logins,
creds, newb, netCnt, TOD, activity, logdate,
COALESCE (Month, 'GT') as MonthNM
FROM (SELECT logdate
,activity
,DATE( logdate ) AS Date
,DAYOFWEEK( logdate ) AS DOW
,WEEK( logdate,0 ) AS Week
,YEAR( logdate ) AS Year
,MONTHNAME ( logdate ) AS Month
,MONTH( logdate ) AS monum
,CONVERT( netID,UNSIGNED INTEGER ) AS netID
,COUNT( callsign ) AS Logins
,COUNT( IF(creds <> '',1,NULL) ) AS creds
,COUNT( IF(comments LIKE '%first log in%',1,NULL) ) AS newb
,count( DISTINCT netID ) AS netCnt
,SUM( DISTINCT netID) AS allCnt
,SEC_TO_TIME( SUM(timeonduty) ) AS TOD
FROM NetLog
WHERE netID <> 0
AND activity NOT LIKE '%TEST%'
AND netcall LIKE '%W0KCN%'
AND substr(logdate,1,4) = 2017
GROUP BY Month, netID WITH ROLLUP ) AS t
ORDER BY
CASE
WHEN MonthNM = 'GT' THEN 1
ELSE 0
END
,monum
,logins