我使用如下查询获取数据:
SELECT `product_name`, `Number of Cases` FROM `myTable` where `color` = 'red' order by `Number of Cases` DESC";
如果我var_dump
:
array(2) {
[0]=> array(4) { ["product_name"]=> string(5) "23418" [0]=> string(5) "23418" ["Number of Cases"]=> string(3) "434" [1]=> string(3) "434" }
[1]=> array(4) { ["product_name"]=> string(5) "79746" [0]=> string(5) "79746" ["Number of Cases"]=> string(3) "372" [1]=> string(3) "372" }
}
以上是一个例子,但很明显,我在真实表格中有更多行。
这就是我要做的事情......
获取"案例数量"的所有值并将它们分解为五分之一(每个桶中有5个桶,每个桶中有相同数量的值;#34;)或十分位数(每个桶中有10个具有相同数值的桶,#34;桶")。我需要为每个五分位数或十分位数返回最高值(对于"案例数和#34;)。
我看到流程是这样的:
我知道这些步骤,但我无法将它们翻译成可用的PHP。
任何见解都会有所帮助。
感谢。
答案 0 :(得分:1)
您可以使用变量在MySQL中的数据中添加tile
列。以下是五分位数和十分位数的示例:
SELECT t.*,
floor((seqnum - 1) * 5 / @rn) as tile_5,
floor((seqnum - 1) * 10 / @rn) as tile_10
FROM (SELECT `product_name`, `Number of Cases`, (@rn := @rn + 1) as seqnum
FROM `myTable` CROSS JOIN
(SELECT @rn := 0) params
WHERE `color` = 'red'
ORDER BY `Number of Cases` DESC
) t
编辑:
以上内容应该有效,但@rn
可能会发生一些时髦的事情。如果是这样的话:
SELECT t.*,
floor((seqnum - 1) * 5 / x.cnt) as tile_5,
floor((seqnum - 1) * 10 / x.cnt) as tile_10
FROM (SELECT `product_name`, `Number of Cases`, (@rn := @rn + 1) as seqnum
FROM `myTable` CROSS JOIN
(SELECT @rn := 0) params
WHERE `color` = 'red'
ORDER BY `Number of Cases` DESC
) t CROSS JOIN
(SELECT COUNT(*) as cnt FROM myTable WHERE color = 'red') x;
答案 1 :(得分:0)
对于我的查询,我最终得到了类似的东西,即使在尺寸合适的桌子上也是如此:
SELECT
CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(
GROUP_CONCAT(`number of cases` ORDER BY `number of cases`SEPARATOR ','),
',', 20/100 * COUNT(*) + 1), ',', -1) AS DECIMAL) AS `20th`,
CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(
GROUP_CONCAT(`number of cases` ORDER BY `number of cases`SEPARATOR ','),
',', 40/100 * COUNT(*) + 1), ',', -1) AS DECIMAL) AS `40th`,
CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(
GROUP_CONCAT(`number of cases` ORDER BY `number of cases`SEPARATOR ','),
',', 60/100 * COUNT(*) + 1), ',', -1) AS DECIMAL) AS `60th`,
CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(
GROUP_CONCAT(`number of cases` ORDER BY `number of cases` SEPARATOR ','),
',', 80/100 * COUNT(*) + 1), ',', -1) AS DECIMAL) AS `80th`
FROM `myTable` where `color`="red"
此示例以20%,40%,60%,80%百分位数返回4个数字。这四个数字是特定百分位数的行(number of cases
)的值。
请注意,为了实现这一点,您可能需要增加group_concat_max_len
......这样的事情:
$sessiont = 'SET SESSION group_concat_max_len = 10485760;';
$fixed = $dbh->query($sessiont);