根据MySQL中的条件查找SUM

时间:2015-11-18 12:23:22

标签: mysql

在我的MYSQL表中有1-12类,在类别问题001-300下,a从类别6 + 7 + 8 + 9 + 10示例创建总和 category question correct 1 1 3 1 2 9 2 1 8 6 1 2 7 1 9 12 10 3 结果 category question correct 1 1 3 1 2 9 2 1 8 6+7 1 11 12 10 3

怎么做?

2 个答案:

答案 0 :(得分:1)

您可以使用UNION来实现您的目标。

示例输出:enter image description here

这是SQLFiddle Demo

  SELECT *
  FROM table_name WHERE `category`<6
  UNION

  SELECT (GROUP_CONCAT(`category` SEPARATOR '+')) AS category,
          (GROUP_CONCAT(DISTINCT `question` SEPARATOR '+')) AS question,
          (SUM(`correct`)) AS correct
  FROM table_name WHERE category BETWEEN 6 AND 10

  UNION

  SELECT *
  FROM table_name WHERE `category`>10

希望这有帮助。

答案 1 :(得分:1)

只需将dim g_strSQL as string g_strSQL = "SELECT ID, Desc FROM refTest_Insurance Where statuscode = 'a' ORDER BY InsuranceID ASC" Debug.Print g_strSQL Dim conn As ADODB.Connection Dim g_RS As ADODB.Recordset ' db_file contains the Access database's file name. ' Open a connection. Set conn = New ADODB.Connection conn.ConnectionString = "Your connection string here" conn.Open ' Get the records. Set g_RS = conn.Execute(g_strSQL, , adCmdText) 'Set URLs = New Collection Do While Not g_RS.EOF List1.AddItem g_RS!Desc 'URLs.Add CStr(g_RS!Id) g_RS.MoveNext Loop ' Close the recordset and connection. g_RS.Close conn.Close group by声明一起使用:

case

实际上,这可以简化为:

select (case when min(category) = max(category) then min(category)
             else group_concat(category order by category separator '+')
        end) as category,
       question, sum(correct) as correct
from mytable
group by (case when category in (6, 7, 8, 9, 10) then -1 else category end),
         question;