我正在尝试在我们的售票网站上整理用户的实时视图。
目前,我在网站上有2个会话(Session col)。我当前的查询返回以下内容:
EVENTID EVENT Session SessionOpened SessionLength NumberofTix
1619 BB King 11 2013-01-28 09:34:16.300 -2 2
1622 BB King 12 2013-01-28 09:36:55.073 0 1
1622 BB King 12 2013-01-28 09:36:55.077 0 3
但是,它应该是这样的:
EVENTID EVENT Session SessionOpened SessionLength NumberofTix
1619 BB King 11 2013-01-28 09:34:16.300 -2 2
1622 BB King 12 2013-01-28 09:36:55.073 0 4
为什么Session 12返回2行-1,1张票,1张3票?
查询:
SELECT distinct set_eSRO_Event as EventID, shName as EventName, setSRO_UID as SRO_SessionID, setDateTime as SessionStarted,
DATEDIFF(mi, getDate(), setDateTime) as SessionTimer, Count(*) AS NumberofTickets FROM SessionTickets
INNER JOIN Shows on shCode = setShowCode
WHERE setStatus = 0
GROUP BY setsro_UID, shName, set_eSRO_Event, setDateTime
答案 0 :(得分:1)
你的结果列和查询的别名不一致,很难说。我认为setDateTime是不同的(= SessionStarted或SessionOpened)。当您按setDatetime分组时,如果它们不同=>两行。
因此,为setDatetime添加MIN
聚合函数(如在“想要的”结果中),并从GROUP BY中删除setDatetime
SELECT set_eSRO_Event as EventID,
shName as EventName,
setSRO_UID as SRO_SessionID,
MIN(setDateTime) as SessionStarted,
DATEDIFF(mi, getDate(), MIN(setDateTime)) as SessionTimer,
COUNT(*) AS NumberofTickets
FROM SessionTickets
INNER JOIN Shows on shCode = setShowCode
WHERE setStatus = 0
GROUP BY setsro_UID, shName, set_eSRO_Event
答案 1 :(得分:1)
如果不知道哪个列属于哪个表,以及SQL Server的版本,您可以尝试以下查询:
SELECT EventID,
EventName,
SRO_SessionID,
MIN(SessionStarted) SessionStarted,
SessionTimer,
SUM(NumberofTickets) NumberofTickets
FROM ( SELECT set_eSRO_Event as EventID,
shName as EventName,
setSRO_UID as SRO_SessionID,
setDateTime as SessionStarted,
DATEDIFF(mi, getDate(), setDateTime) as SessionTimer,
Count(*) AS NumberofTickets
FROM SessionTickets
INNER JOIN Shows
ON shCode = setShowCode
WHERE setStatus = 0
GROUP BY set_eSRO_Event, shName, setSRO_UID, setDateTime,
DATEDIFF(mi, getDate(), setDateTime)) A
GROUP BY EventID, EventName, SRO_SessionID, SessionTimer