给出以下MySQL表:
| id | category | Hour | quantity|
| 0 | Sunday | 10 | 32 |
| 0 | Sunday | 11 | 19 |
| 0 | Sunday | 12 | 48 |
| 0 | Sunday | 19 | 7 |
| 1 | Monday | 09 | 45 |
| 1 | Monday | 10 | 17 |
| 1 | Monday | 12 | 18 |
| 2 | Tuesday | 08 | 16 |
| 2 | Tuesday | 09 | 39 |
| 2 | Tuesday | 10 | 24 |
| 2 | Tuesday | 11 | 37 |
| 2 | Tuesday | 12 | 40 |
我需要计算第五列,它必须是"数量"通过id的行数:对于0,有4行,对于1 3行,对于2 5行。
| id | category | Hour | quantity| avg |
| 0 | Sunday | 10 | 32 | 8 |
| 0 | Sunday | 11 | 19 | 4.75 |
| 0 | Sunday | 12 | 48 | 12 |
| 0 | Sunday | 19 | 7 | 1.75 |
| 1 | Monday | 09 | 45 | 15 |
| 1 | Monday | 10 | 17 | 5.7 |
| 1 | Monday | 12 | 18 | 6 |
| 2 | Tuesday | 08 | 16 | 3.2 |
| 2 | Tuesday | 09 | 39 | 7.8 |
| 2 | Tuesday | 10 | 24 | 4.8 |
| 2 | Tuesday | 11 | 37 | 7.4 |
| 2 | Tuesday | 12 | 40 | 8 |
如何在MySQL查询中获得结果?
第一个表是此查询的结果:
select id, category, Hour, count(*) as quantity
FROM table_1
GROUP by id, Hour ORDER by id, Hour;
这是我试过的,为了得到每个id出现的行数,但是我得到一个大数字,在前一个查询中id = 0次出现而不是id = 0行的计数:
select id, Hour, count(id) as q
FROM table_1
GROUP by id
这是mySql 5.6。
答案 0 :(得分:2)
这真的非常难看和繁琐,但这是获得结果而没有主键可以使用的唯一方法:
SELECT
t.id,
t.category,
t.hour,
quantity,
ROUND(quantity/count,2) AS avg
FROM table_1 t
JOIN (SELECT
id, Hour, count(*) as quantity
FROM table_1
GROUP by id, category, Hour) AS qty
ON t.id = qty.id AND t.hour = qty.hour
JOIN (SELECT
id, count(distinct hour) as count
FROM table_1
GROUP BY id) as counts
ON t.id = counts.id
GROUP BY id, hour;
至少在猜测原始数据集的样子时,它似乎在本地工作。
然而,可能有一种更简单的方式。
编辑:第二次检查时,'数量'子查询实际上并没有增加太多我能看到的内容,因此可以用'count(*)'替换,使其更加优化查询:
SELECT
t.id,
t.category,
t.hour,
count(*) as quantity,
ROUND(count(*)/count,2) AS avg
FROM table_1 t
JOIN (SELECT
id, count(distinct hour) as count
FROM table_1
GROUP BY id) as counts
ON t.id = counts.id
GROUP BY id, hour;
答案 1 :(得分:0)
您需要在仅按id
分组的子查询中进行计数。将子查询加入主查询并进行除法。
SELECT id, category, hour, COUNT(*) AS quantity, COUNT(*)/count AS avg
FROM table_1
JOIN (SELECT id, COUNT(DISTINCT hour) AS count
FROM table_1
GROUP BY id) AS counts
ON table_1.id = counts.id
GROUP BY table_1.id, table_1.hour
ORDER BY table_1.id, table_1.hour