我需要使用MySQL生成以下输出,它可以计算可用的总票数和每个事件的总票数;
event_id event_name start_date tickets_available tickets_sold
-------------------------------------------------------------------------
1 Test Event 1 2017-04-01 200 20
2 Test Event 2 2017-04-25 100 30
我的表格如下;
表:事件
event_id user_id event_name start_date event_active
-------------------------------------------------------------------------
1 47 Test Event 1 2017-04-01 0
2 47 Test Event 2 2017-04-25 0
表:ticket_types
ticket_type_id event_id ticket_type quantity_released quantity_remaining
---------------------------------------------------------------------------
1 1 General 100 90
2 1 VIP 100 90
3 2 General 50 30
4 2 VIP 50 40
到目前为止,这是我的SQL查询;
SELECT events.event_id, events.event_name, events.start_date, events.event_active,
(
SELECT SUM(ticket_types.quantity_released)
FROM ticket_types
WHERE ticket_types.event_id = events.event_id
) AS tickets_available,
(
SELECT (ticket_types.quantity_released - ticket_types.quantity_remaining)
FROM ticket_types
WHERE ticket_types.event_id = events.event_id
) AS tickets_sold
FROM events
INNER JOIN ticket_types
ON events.event_id=ticket_types.event_id
WHERE user_id = 47;
但是,这不起作用,因为ticket_available和tickets_sold列的逻辑不正确。
有人可以帮我解决这个问题吗?
答案 0 :(得分:2)
SELECT EVENTS.EVENT_ID
, EVENTS.EVENT_NAME
, EVENTS.START_DATE
, SUM(TICKET_TYPES.QUANTITY_RELEASED) AS TICKETS_AVAILABLE
, SUM(TICKET_TYPES.QUANTITY_RELEASED) - SUM(TICKET_TYPES.QUANTITY_REMAINING) AS TICKETS_SOLD
FROM EVENTS
INNER JOIN TICKET_TYPES
ON EVENTS.EVENT_ID = TICKET_TYPES.EVENT_ID
GROUP BY EVENTS.EVENT_ID
, EVENTS.EVENT_NAME
, EVENTS.START_DATE;
答案 1 :(得分:0)
由于我缺乏SQL格式的知识,因此格式不是很好,但这可能是您的解决方案。
SELECT events.event_id,
events.event_name,
events.start_date,
events.event_active,
SUM(ticket_types.quantity_released) AS available,
SUM(ticket_types.quantity_released) - SUM(ticket_types.quantity_remaining) AS sold
FROM events
INNER JOIN ticket_types
ON events.event_id = ticket_types.event_id
GROUP BY events.event_id
WHERE user_id = 47;