加入问题

时间:2014-04-25 04:13:25

标签: mysql sql

SELECT a.AuditoriumName,
     COUNT(d.StudentID) as Total_Visits 
                          from Auditorium a
     INNER JOIN AudiReservation c ON b.AudiID=c.AudiID
     INNER JOIN OrderHistory d on c.OrderID=d.OrderID
GROUP BY d.StudentID;

Auditorium - AudiID(pk), AudiName
AudiReservation - ReservationID(pk),AudiID(fk),OrderID(fk)
OrderHistory - OrderID(pk),StudentID(fk)
Student - StudentID(pk)

这里的问题是,它不能唯一地识别学生。我认为的主要问题是因为AudiReservation与OrderHistory有多对一的关系。因此,当输出到来时,我得到重复的VenueNames和VenueID。我尝试将AudiReservation的OrderID分组,以便仅将唯一值与OrderHistory匹配。但这似乎不起作用。有人可以帮忙吗?

输入 -

学生 -

StudentID    Student_Name
1            Matt
2            Victor

订单历史记录 -

OrderID      StudentID
101            1
102            1
103            1
104            2
104            2

AudiReservation -

Reservation    OrderID    AudiID
001             101        AUDI01
002             102        AUDI01
003             103        AUDI01
003             104        AUDI02
004             101        AUDI02
005             102        AUDI02

礼堂

AUDI01        Audi1-Tower of London
AUDI02        Audi2-London Bridge

预期产出 -

Auditorium  Name                Total Students Visit
AUDI01       Tower of London     2
AUDI02       London Bridge       2

学生总数此次访问是参观礼堂的独特学生总数。

3 个答案:

答案 0 :(得分:1)

您尝试group使用Audi_id并计算distinct名学生

SELECT a.AuditoriumName,
     COUNT( distinct d.StudentID) as Total_Visits 
                          from Auditorium a
     INNER JOIN AudiReservation c ON a.AudiID=c.AudiID
     INNER JOIN OrderHistory d on c.OrderID=d.OrderID
GROUP BY a.AudiID;

答案 1 :(得分:0)

  

因此,当输出到来时,我会得到重复的VenueNames和VenueIDs

您可以使用COUNT(DISTINCT the_unique_id_field_your_need)。像这样COUNT(DISTINCT VenueID)。我不知道哪个表有列可以选择合适的别名。

答案 2 :(得分:0)

查看sqlfiddle

中的执行情况
select D.AudiID,E.AuditoriumName,D.Total_Visits
from Auditorium E,
(
    select C.AudiID,count(distinct C.StudentId) as Total_Visits
    from 
    (
        select A.AudiID,B.StudentID
        from AudiReservation A, OrderHistory B
        where A.orderID = B.orderID
    )C
    group by C.AudiID
)D
where E.AudiID = D.AudiID