我必须在3个表格上使用LEFT JOIN
:UNITS
,ROOMS_CHECK_IN
和COMMENTS
。基本上我想显示UNITS
并且每个单位的房间数量都会检查和评论的数量。但是当我正在办理房间登记和评论计数时,我得到相同的4位数字。如果我将单个左连接分开2个查询,它可以正常工作。
以下是查询:
SELECT u.ID,
u.unit_name,
count(c.checkin_status) as total_chekin ,
count(com.ID) as total_comment ,
h.hospital_name
FROM HOSPITALS h, UNITS u
LEFT OUTER JOIN ROOMS_CHECK_IN c ON c.unit_id = u.ID AND c.room_status=0
LEFT OUTER JOIN COMMENTS com ON com.unit_id = u.ID
WHERE h.ID = u.hospital_id AND u.hospital_id=3
GROUP BY u.ID;
请帮助。
答案 0 :(得分:2)
从不在JOIN
子句中使用逗号。 始终使用明确的count(distinct)
上下文。
然后,您可能想要SELECT u.ID, u.unit_name,
count(distinct c.checkin_status) as total_chekin,
count(distinct com.ID) as total_comment,
h.hospital_name
FROM HOSPITALS h JOIN
UNITS u
ON h.ID = u.hospital_id LEFT OUTER JOIN
ROOMS_CHECK_IN c
ON c.unit_id = u.ID AND c.room_status = 0 LEFT OUTER JOIN
COMMENTS com
ON com.unit_id = u.ID
WHERE u.hospital_id = 3
GROUP BY u.ID, u.unit_name, h.hospital_name;
(或在加入之前聚合):
Private Sub Application_Reminder(ByVal Item As Object)
If TypeOf Item Is Outlook.TaskItem Then
If Not Item.Subject = "Send Report" Then
Exit Sub
End If
End If
GetTemp Item ' call sub
End Sub
Private Sub GetTemp(ByVal Item As TaskItem)
Dim xlApp As Excel.Application
Dim xlBook As Workbook
Set xlApp = New Excel.Application
Set xlBook = xlApp.Workbooks.Open("C:\Temp\Excel_File.xlsm") ' update with Excel name
xlApp.Visible = True
' // Run Macro in Excel_File
xlBook.Application.Run "Module1.CheckDates" ' Update with subname
Set xlApp = Nothing
Set xlBook = Nothing
End Sub