从整个表中获取平均字符串值

时间:2017-10-23 14:48:11

标签: mysql

我想知道如何从表中获取平均字符串(数字也被视为字符串)并将每个字符串值插入一行。

例如:

Day    Hours Break
Monday  6     1
Monday  4    0.5
Monday  6     1
Tuesday 8     2

返回的值为:

Monday
6
1 

然后,值将在预先存在的行中更新,例如;

Name  Day    Hours Break
James Monday  6     1

我已经尝试将下面的MySQL查询更改为有效,但它没有,所以这是原始的:

SELECT       `day`,
         COUNT(`day`) AS `value_occurrence` 
FROM     `worked`
GROUP BY `day`
ORDER BY `value_occurrence` DESC
LIMIT    1;

编辑: 我的榜样很糟糕。

id  name         day       hours   break 
0  mostfrequent 
1  James        Monday     6        1
2  Joe          Wednesday  6        1
3  Jack         Tuesday    8        2
4  Sam          Monday     4       0.5

然后将值“星期一”,“6”和“1”插入到频繁的

2 个答案:

答案 0 :(得分:0)

试试这个:

select day,
    (select hours from worked w where w.day = w1.day
        group by hours order by count(*) desc limit 1) as hours, 
    (select break from worked w where w.day = w1.day
        group by break order by count(*) desc limit 1) as break
from worked w1
where day = (select day from worked w
                group by day order by count(*) desc limit 1)
group by day;

where子句选择最频繁的一天,然后相关子查询选择当天最频繁的小时数和休息时间。

答案 1 :(得分:0)

为什么你没有立刻提到列数?

查询3"最常见的"值是3个查询,或下面提到的解决方案。将此缩放为32列 - 嗯,子选择和独立查询似乎都没有帮助。

在这种情况下,我肯定会使用您正在使用的语言中的某种foreach? (PHP?)

所以,首先:获取所有列。 第二:每列,数和&插入:

示例代码:

$valueArray() = array();
$dbConnection->Query("SHOW COLUMNS FROM mytable");
while ($row = $dbConnection->getResultRow()){
   $column = $row["Field"]; //Static field name when using SHOW COLUMNS

   $actualQuery = "SELECT $column, count(*) as ct FROM mytable GROUP BY $column ORDER BY count(*) LIMIT 0,1";
   $dbConnection2->Query($actualQuery);
   $subRow = $dbConnection2->getResultRow();

   //now delivers the count value per $Field.
   $valueArray[$column] = array("key" => $subRow[$column], "value" => $subRow["ct"];
}

//finally - assuming fields "day, hours, break"
array(
  "day" => ( key => "Monday", value => 2),
  "hours" => (key => "8", value => 2),
  "break" => (key => "1", value => 2)
)

(未经测试,但这样的事情应该可以解决)