我有一个当前的SQL查询,内容如下:
SELECT
WEEK,
SUM(CASE WHEN WEEK = '$week1' THEN 1 ELSE 0 END) AS week_1_total,
SUM(CASE WHEN WEEK = '$week2' THEN 1 ELSE 0 END) AS week_2_total,
SUM(CASE WHEN WEEK = '$week3' THEN 1 ELSE 0 END) AS week_3_total,
SUM(CASE WHEN WEEK = '$week4' THEN 1 ELSE 0 END) AS week_4_total,
SUM(CASE WHEN WEEK = '$week1' AND TYPE = 'refund' THEN 1 ELSE 0 END) AS week_1_refunds,
SUM(CASE WHEN WEEK = '$week2' AND TYPE = 'refund' THEN 1 ELSE 0 END) AS week_2_refunds,
SUM(CASE WHEN WEEK = '$week3' AND TYPE = 'refund' THEN 1 ELSE 0 END) AS week_3_refunds,
SUM(CASE WHEN WEEK = '$week4' AND TYPE = 'refund' THEN 1 ELSE 0 END) AS week_4_refunds,
SUM(CASE WHEN WEEK = '$week1' AND TYPE = 'closure' THEN 1 ELSE 0 END) AS week_1_closures,
SUM(CASE WHEN WEEK = '$week2' AND TYPE = 'closure' THEN 1 ELSE 0 END) AS week_2_closures,
SUM(CASE WHEN WEEK = '$week3' AND TYPE = 'closure' THEN 1 ELSE 0 END) AS week_3_closures,
SUM(CASE WHEN WEEK = '$week4' AND TYPE = 'closure' THEN 1 ELSE 0 END) AS week_4_closures,
SUM(CASE WHEN WEEK = '$week1' AND history LIKE '%rejected%' THEN 1 ELSE 0 END) AS week_1_rejections,
SUM(CASE WHEN WEEK = '$week2' AND history LIKE '%rejected%' THEN 1 ELSE 0 END) AS week_2_rejections,
SUM(CASE WHEN WEEK = '$week3' AND history LIKE '%rejected%' THEN 1 ELSE 0 END) AS week_3_rejections,
SUM(CASE WHEN WEEK = '$week4' AND history LIKE '%rejected%' THEN 1 ELSE 0 END) AS week_4_rejections
FROM
my_table
WHERE
YEAR = '$SafeFY' AND period = '$SafePeriod'
GROUP BY
WEEK
此查询有效,并向我获取了我想要的数据,但是由于我做的方式,这些数据已经遍历。
我只是这样做,因为这是我知道的唯一方法。我想像这样在PHP循环中使用结果:
echo '<table><opening tags> <etc...>'
while($Row = $Result->fetch_array(MYSQLI_ASSOC)) {
//HTML table rows with $Row['stuff'] here.
}
echo '</etc...></closing tags></table> '
但是数据是错误的打印表格的方式,如下所示:
| Week | Total | Refunds | Closures | Rejections |
| 1 | 44 | 32 | 12 | 3 |
| 2 | 40 | 21 | 19 | 6 |
| 3 | 40 | 22 | 18 | 3 |
| 4 | 41 | 32 | 11 | 6 |
我不介意更改查询以在没有数据透视的情况下获得所有相同的结果,因此我可以像以前那样循环遍历它们,或者不使用PHP数组进行操作以使我可以遍历此查询结果,无论哪种更容易/更好。怎么样?
答案 0 :(得分:0)
好吧,我又看了一遍,我想我只是在加倍努力。
继续以下假设: 1)数据库通常比PHP更擅长对数据进行排序/组织,因此更改查询可能比事后更改数组更好。 2)如果我希望结果有5列,则可能需要在语句中有5个选择
然后,我查看了GROUP BY部分,并意识到无论如何它已经将结果按周进行了拆分,因此我按总和进行了精简,然后GROUP BY部分将结果分成了几周,没有需要每周在选定部分中手动汇总。
SELECT
WEEK,
SUM(CASE WHEN YEAR = '2019' THEN 1 ELSE 0 END) AS total,
SUM(CASE WHEN TYPE = 'refund' THEN 1 ELSE 0 END) AS refunds,
SUM(CASE WHEN TYPE = 'closure' THEN 1 ELSE 0 END) AS closures,
SUM(CASE WHEN history LIKE '%rejected%' THEN 1 ELSE 0 END) AS rejections
FROM
my_table
WHERE
YEAR = '$SafeFY' AND period = '$SafePeriod'
GROUP BY
WEEK