当我传递查询中所需的所有值时,返回正确的结果。但是当我只传递ID时,我得到一个空的结果集。在这种情况下是不是应该忽略类型并仍然返回正确的值?
你能帮我解决这个问题并指出问题中的问题。
SELECT 'elementary_school' AS type, elementary_school AS obj, COUNT(*) AS count
FROM data
WHERE data.report_id = ReportId
AND (data.book_section = type
OR data.book_section IS NULL
OR data.book_section = ''
)
GROUP BY elementary_school
UNION
SELECT 'middle_school' AS type, middle_school AS obj, COUNT(*) AS count
FROM data
WHERE data.report_id = ReportId
AND (data.book_section = type
OR data.book_section IS NULL
OR data.book_section = ''
)
GROUP BY middle_school
UNION
SELECT 'high_school' AS type, high_school AS obj, COUNT(*) AS count
FROM data
WHERE data.report_id = ReportId
AND (data.book_section = type
OR data.book_section IS NULL
OR data.book_section = ''
)
GROUP BY high_school
UNION
SELECT 'lot_sqft' AS type, lot_sqft AS obj, COUNT(*) AS count
FROM data
WHERE data.report_id = ReportId
AND (data.book_section = type
OR data.book_section IS NULL
OR data.book_section = ''
)
GROUP BY lot_sqft
ORDER BY count, type
答案 0 :(得分:0)
您可以简化查询:
SELECT t.type,
(CASE WHEN t.type = 'elementary_school' THEN elementary_school
WHEN t.type = 'middle_school' THEN middle_school
WHEN t.type = 'high_school' THEN high_school
WHEN t.type = 'lot_sqft' THEN lot_sqft
END) AS obj, COUNT(*) AS count
FROM data d CROSS JOIN
(SELECT 'elementary_school' AS type UNION ALL
SELECT 'middle_school' AS type UNION ALL
SELECT 'high_school' AS type UNION ALL
SELECT 'lot_sqft' AS type
) t
WHERE d.report_id = @ReportId AND
(d.book_section = @type OR
d.book_section IS NULL OR
d.book_section = ''
)
GROUP BY t.type. obj;
我已经强调了似乎是"参数"使用@
来阐明它们是参数而不是表格中的列。
如果要检查NULL
值,请将逻辑更改为:
WHERE (d.report_id = @ReportId OR @ReportId IS NULL) AND
(d.book_section = @type OR
d.book_section IS NULL OR
d.book_section = ''
)
答案 1 :(得分:0)
AND (data.book_section = type
OR data.book_section IS NULL
OR data.book_section = ''
)
转换为:
AND (data.book_section = type
OR type IS NULL
OR type = ''
)
因为我只想检查它是否是传递param的'type'是空的还是null。无论如何,谢谢每个试图帮助的人。欢呼声。