我正在尝试获取此查询...
SELECT `Num_1`, COUNT(`Num_1`) AS `value_occurrence` FROM numbers WHERE MONTH(`Dates`) = 1 AND YEAR(`Dates`) = 1995 GROUP BY `Num_1` ORDER BY `value_occurrence` DESC
但对于多个列,如'Num_1','Num_2','Num_3','Num_4','Num_5'并返回每列的出现,例如'num_1_occurrence','num_2_occurrence','num_3_occurrence', 'num_4_occurrence','num_5_occurrence'以及指定日期内的所有内容。
我曾尝试过使用......
SELECT `Num_1`,`Num_2`, `Num_3`,`Num_4`,`Num_5`,COUNT(`Num_1`,`Num_2`,`Num_3`,`Num_4`,`Num_5`) AS `num_1_occurrence`,`num_2_occurrence`,`num_3_occurrence`, `num_4_occurrence`,`num_5_occurrence`FROM numbers WHERE MONTH(`Dates`) = 1 AND YEAR(`Dates`) = 1995
但只是犯了错误,我已经搜索了好几天,但没有找到正确的方法。
答案 0 :(得分:0)
我这样做:
SELECT n.num
, MAX(IF(n.q='n1',n.cnt,NULL)) AS num_1_occurrence
, MAX(IF(n.q='n2',n.cnt,NULL)) AS num_2_occurrence
, MAX(IF(n.q='n3',n.cnt,NULL)) AS num_3_occurrence
FROM (
SELECT 'n1' AS q
, n1.Num_1 AS num
, COUNT(n1.Num_1) AS cnt
FROM numbers n1
WHERE n1.Dates >= '1995-01-01'
AND n1.Dates < '1995-01-01' + INTERVAL 1 MONTH
GROUP BY n1.Num_1
UNION ALL
SELECT 'n2' AS q
, n2.Num_2 AS num
, COUNT(n2.Num_2) AS cnt
FROM numbers n2
WHERE n2.Dates >= '1995-01-01'
AND n2.Dates < '1995-01-01' + INTERVAL 1 MONTH
GROUP BY n2.Num_2
UNION ALL
SELECT 'n3' AS q
, n3.Num_3 AS num
, COUNT(n3.Num_3) AS cnt
FROM numbers n3
WHERE n3.Dates >= '1995-01-01'
AND n3.Dates < '1995-01-01' + INTERVAL 1 MONTH
GROUP BY n3.Num_3
) n
GROUP BY n.num
ORDER BY GREATEST(num_1_occurrence,num_2_occurrence,num_3_occurrence) DESC
答案 1 :(得分:0)
我这里只做Num_1和Num_2,但我认为这是你正在寻找或关闭的。这将为您提供“高”格式的列表,其中包含原始列名称,该列中的值以及该列中该值的计数...
SELECT 'Num_1' AS field_name, Num_1 AS value, value_count
FROM (SELECT Num_1, COUNT(Num_1) AS value_count
FROM numbers
GROUP BY Num_1) AS num1_counts
WHERE MONTH(`Dates`) = 1 AND YEAR(`Dates`) = 1995
UNION
SELECT 'Num_2' AS field_name, Num_2 AS value, value_count
FROM (SELECT Num_2, COUNT(Num_2) AS value_count
FROM numbers
GROUP BY Num_2) AS num2_counts
WHERE MONTH(`Dates`) = 1 AND YEAR(`Dates`) = 1995