我有这段代码:
Const SQLExpression As String = "SELECT site.siteid AS 'SITE ID', site_name AS 'SITE', COUNT(DISTINCT date) AS 'Attendance', 75 * (SELECT COUNT(DISTINCT date) AS 'Attendance') AS 'Total' FROM record LEFT JOIN learner on record.idNumber = learner.idNumber LEFT JOIN site ON learner.siteid=site.siteid WHERE MONTH(date) = MONTH(CURRENT_DATE()) AND YEAR(date) = YEAR(CURRENT_DATE()) GROUP BY record.idNumber "
它返回以下数据:Table
我想获得以下内容:
+----------+--------------------------------+
| SITE ID | SITE | Attendance |
+-------------------------------------------+
| 314 | Broad Market1 | 34 |
| 254 | Catherine Booth.. | 36 |
| 289 | Ceter for Entrep..| 27 |
| 330 | Climamark Morem.. | 7 |
+-------------------------------------------+
我尝试过以下代码:
"SELECT siteid AS 'SITE ID', site_name AS 'SITE', SUM(DISTINCT Attendance) AS 'Attendance' FROM (SELECT COUNT(DISTINCT record.date)AS 'Attendance' FROM record LEFT JOIN learner on record.idNumber = learner.idNumber LEFT JOIN site ON learner.siteid=site.siteid WHERE MONTH(date) = MONTH(CURRENT_DATE()) AND YEAR(date) = YEAR(CURRENT_DATE()) GROUP BY record.idNumber) As Attendance, site GROUP BY siteid "
我得到以下数据:TableResult
答案 0 :(得分:0)
假设在表站点中您拥有主键ID,您应该使用内部联接INNER JOIN站点Attendance.siteid = site.id(而不是交叉联接(出勤,没有站点的站点))
"SELECT siteid AS 'SITE ID'
, site_name AS 'SITE'
, SUM(DISTINCT Attendance) AS 'Attendance'
FROM (
SELECT COUNT(DISTINCT record.date) AS 'Attendance'
FROM record
LEFT JOIN learner on record.idNumber = learner.idNumber
LEFT JOIN site ON learner.siteid=site.siteid
WHERE MONTH(date) = MONTH(CURRENT_DATE())
AND YEAR(date) = YEAR(CURRENT_DATE())
GROUP BY record.idNumber ) As T_Attendance
INNER JOIN site T_Attendance.siteid = site.id
GROUP BY siteid "