SQL聚合函数值乘法

时间:2015-08-06 02:20:30

标签: mysql sql group-by aggregate multiplication

在单个查询中,我想在两个不同表格的两个不同列上public class Program { public static void Main() { new Program().Execute(); } public void Execute() { // lock objects this.fixErrorLock = new object(); this.isLoggingInLock = new object(); var objectsToIterate = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 }; objectsToIterate.AsParallel().ForAll(this.DoWork); } private object isLoggingInLock; private object fixErrorLock; private bool isLoggingIn; public bool IsThereAnyThreadLoggingIn() { lock (this.isLoggingInLock) { // If no thread is logging-in, the one who asked is going to log-in if (!this.isLoggingIn) this.isLoggingIn = true; return this.isLoggingIn; } } public void DoWork(int myParam) { try { if (myParam % 4 == 0) throw new Exception(); } catch (Exception ex) { // Is the equivalent of 'is the first thread to hit here?' bool canLogIn = this.IsThereAnyThreadLoggingIn(); // Every thread with error will stop here lock (fixErrorLock) { // But only the first one will do the login process again if (canLogIn) { // Inside the login method the variable responsible for the 'isFirstThread' is restored to false this.LogIn(); } } this.DoWork(myParam-1); } } public void LogIn() { Thread.Sleep(100); lock (this.isLoggingInLock) { // The login is done this.isLoggingIn = false; } } } COUNT

问题是GROUP_CONCAT返回的数字乘以COUNT中不同项目的数量,而GROUP_CONCAT结果中,每个不同的项目乘以数字COUNT应该返回。

以下是查询:

GROUP_CONCAT

这是一个SQL Fiddle所以这个更清晰/可测试。

结果看起来像这样:

SELECT e.id, GROUP_CONCAT(c.id SEPARATOR ',') AS category_ids, COUNT(a.id) AS numberAttenders, e.event_capacity
FROM events e
LEFT JOIN attendees a ON a.event_id=e.id,
categories c,
event_categories ec
WHERE  e.id=ec.event_id 
AND ec.category_id=c.id 
GROUP BY e.id
HAVING numberAttenders < e.event_capacity OR e.event_capacity=0

当我想要这样的东西时:

id 1
category_ids 1,2,1,2
numberAttenders 4
event_capacity 10

我和id 1 category_ids 1,2 numberAttenders 2 event_capacity 10 玩了一点但是没有成功的结果。

1 个答案:

答案 0 :(得分:2)

您将获得每个活动的与会者和类别的笛卡尔积。最好的解决方案是在进行连接之前聚合表

SELECT e.id, ec.category_ids, a.NumAttendees, e.event_capacity
FROM events e LEFT JOIN
     (SELECT a.event_id, COUNT(*) as NumAttendees
      FROM attendees a
      GROUP BY a.event_id
     ) a
     ON a.event_id = e.id LEFT JOIN
     (SELECT ec.event_id, GROUP_CONCAT(c.id SEPARATOR ',') as category_ids
      FROM event_categories ec JOIN
           categories c
           ON ec.category_id = c.id 
      GROUP BY ec.event_id
     ) ec
     ON  e.id=ec.event_id 
HAVING NumAttendees < e.event_capacity OR e.event_capacity = 0;

Here是一个SQL小提琴。