我有两张表文件和 poi_data 。文档包含两种类型的表单 ETP 和 FP10 。我想基于数字和下面查询中显示的两个别名的总和来计算两种形式。不幸的是它不起作用。
Document Table (id,title ,type ,status)
poi_data Table (poi_id, doc_id, form_number, status)
SELECT
COUNT(DISTINCT CASE WHEN documents.title LIKE '%ETP%' THEN poi_data.form_number END) AS form_count_one,
COUNT(DISTINCT CASE WHEN documents.title LIKE '%FP10%' THEN poi_data.form_number END) AS form_count_two,
SUM(form_count_one + form_count_two) as total_form_count FROM poi_data
LEFT JOIN documents ON (poi_data.doc_id = documents.id AND documents.status = 1)
WHERE poi_data.pid = 781 AND poi_data.poi_id = 8
答案 0 :(得分:0)
只需使用子查询:
SELECT form_count_one, form_count_two
(form_count_one + form_count_two) as total_form_count
FROM (SELECT COUNT(DISTINCT CASE WHEN d.title LIKE '%ETP%' THEN pd.form_number END) AS form_count_one,
COUNT(DISTINCT CASE WHEN d.title LIKE '%FP10%' THEN pd.form_number END) AS form_count_two
FROM poi_data pd LEFT JOIN
documents d
ON pd.doc_id = d.id AND d.status = 1
WHERE pd.pid = 781 AND pd.poi_id = 8
) d
答案 1 :(得分:0)
选择
(COUNT(当文件。标题类似'%ETP%',然后poi_data.form_number结束时的DISTINCT案例)+ COUNT(当document.title LIKE'%FP10%'那么poi_data.form_number结束时的DISTINCT案例)AS total_form_count FROM poi_data LEFT JOIN文件ON(poi_data.doc_id = documents.id AND documents.status = 1) 在哪里poi_data.pid = 781 AND poi_data.poi_id = 8
你不需要使用SUM,因为你只想要数不是平均数或什么。然后使用“+”
简单地添加它们答案 2 :(得分:-2)
应该是
select SUM(form_count_one + form_count_two) as total_form_count from (SELECT
COUNT(DISTINCT CASE WHEN documents.title LIKE '%ETP%' THEN poi_data.form_number END) AS form_count_one,
COUNT(DISTINCT CASE WHEN documents.title LIKE '%FP10%' THEN poi_data.form_number END) AS form_count_two,
FROM poi_data
LEFT JOIN documents ON (poi_data.doc_id = documents.id AND documents.status = 1)
WHERE poi_data.pid = 781 AND poi_data.poi_id = 8)alias_name