我正在创建一个查询,该查询从两个表中提取某些用户的视图数。
当找不到结果(即SUM为零)时,我正在努力寻找一种显示“ n / a”的方法。
这是两个表:
个人资料:
-profile_id
-profile_name
观看次数:
-profile_id
-日期
-观看次数
这是查询:
SELECT
p.profile_name,
Jan,
Feb,
Mar,
Apr,
May,
Jun,
Jul,
Aug,
Sep,
Oct,
Nov,
December as 'Dec'
FROM profiles p
LEFT JOIN (SELECT
profile_id,
SUM(IF(MONTH(date) = 1,views,0)) As 'Jan',
SUM(IF(MONTH(date) = 2,views,0)) As 'Feb',
SUM(IF(MONTH(date) = 3,views,0)) As 'Mar',
SUM(IF(MONTH(date) = 4,views,0)) As 'Apr',
SUM(IF(MONTH(date) = 5,views,0)) As 'May',
SUM(IF(MONTH(date) = 6,views,0)) As 'Jun',
SUM(IF(MONTH(date) = 7,views,0)) As 'Jul',
SUM(IF(MONTH(date) = 8,views,0)) As 'Aug',
SUM(IF(MONTH(date) = 9,views,0)) As 'Sep',
SUM(IF(MONTH(date) = 10,views,0)) As 'Oct',
SUM(IF(MONTH(date) = 11,views,0)) As 'Nov',
SUM(IF(MONTH(date) = 12,views,0)) As 'December'
FROM views
WHERE YEAR(date) = '2016'
GROUP BY profile_id) v
ON (p.profile_id = v.profile_id)
ORDER BY p.profile_name
我一直在寻找一种方法,在找不到结果时显示“ n / a”。
这是我现在得到的结果:
+---------------------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+
| Profile 2016 | Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec |
+---------------------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+
| Anna Wintour | 0 | 0 | 0 | 0 | 649693 | 575615 | 658556 | 603785 | 588790 | 0 | 586767 | 639005 |
| Karl Lagerfeld | 635900 | 626585 | 612628 | 586811 | 656580 | 536151 | 598911 | 646069 | 650960 | 594483 | 591757 | 683251 |
| Pierre Alexis Dumas | 629109 | 579499 | 647326 | 585578 | 597296 | 618063 | 603452 | 617052 | 586233 | 588641 | 604276 | 623885 |
| Sandra Choi | 592426 | 590954 | 648027 | 564362 | 633135 | 612299 | 606808 | 629006 | 631480 | 680511 | 565733 | 573343 |
| Tom Ford | 552798 | 603373 | 550430 | 709178 | 662036 | 608399 | 708395 | 610961 | 629205 | 628796 | 616628 | 712198 |
+---------------------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+
答案 0 :(得分:3)
如果您要在一个月内未找到任何视图时显示N/A
,请将每个SUM
更改为以下形式:
COALESCE(SUM(CASE WHEN MONTH(date) = 1 THEN views END), 'N/A') As 'Jan',
这样,如果一个月内没有观看次数,则SUM
的结果将为NULL
(因为CASE
表达式的值将为NULL
),然后COALESCE
会将其转换为N/A
。