希望你能帮助我解决这个我正在努力解决的问题。目前我有以下SQL工作正常,但我想包括end_date列,但即使SYSDATE()< = end_date仍然返回值。这是没有end_date条件和结果的查询:
SELECT pkgCnt.holiday_type_desc, COUNT(DISTINCT pkgCnt.package_heading) AS count
FROM package pkg,
(
SELECT pkg.holiday_type_id, holiday_type_desc, package_heading
FROM package pkg
INNER JOIN holiday_type ht ON pkg.holiday_type_id = ht.holiday_type_id
GROUP BY pkg.holiday_type_id, package_heading
) AS pkgCnt
INNER JOIN holiday_type ht ON pkgCnt.holiday_type_id = ht.holiday_type_id
WHERE pkg.package_heading = pkgCnt.package_heading
GROUP BY pkg.holiday_type_id
ORDER BY pkg.holiday_type_id;
结果如下,这是完美的:
holiday_type_desc count
Bush Breaks 6
City Breaks 5
Golf Breaks 1
Adventure Holidays 3
Beach Holidays 5
Family Holidays 1
但是当我按照下面的查询所示添加end_date时,结果为空:
SELECT pkgCnt.holiday_type_desc, COUNT(DISTINCT pkgCnt.package_heading) AS count
FROM package pkg,
(
SELECT pkg.holiday_type_id, holiday_type_desc, package_heading
FROM package pkg
INNER JOIN holiday_type ht ON pkg.holiday_type_id = ht.holiday_type_id
GROUP BY pkg.holiday_type_id, package_heading
) AS pkgCnt
INNER JOIN holiday_type ht ON pkgCnt.holiday_type_id = ht.holiday_type_id
WHERE pkg.package_heading = pkgCnt.package_heading
AND SYSDATE() <= pkg.end_date
GROUP BY pkg.holiday_type_id
ORDER BY pkg.holiday_type_id;
但我希望查询返回以下内容:
holiday_type_desc count
Bush Breaks 0
City Breaks 0
Golf Breaks 0
Adventure Holidays 0
Beach Holidays 0
Family Holidays 0
答案 0 :(得分:0)
我认为你也可以这样做 -
SELECT pkgCnt.holiday_type_desc,
COUNT(DISTINCT pkgCnt.package_heading) AS count,
sum(case
when SYSDATE() <= pkg.end_date then
1
else
0
end) as count_after_codition
FROM package pkg,
(SELECT pkg.holiday_type_id, holiday_type_desc, package_heading
FROM package pkg
INNER JOIN holiday_type ht
ON pkg.holiday_type_id = ht.holiday_type_id
GROUP BY pkg.holiday_type_id, package_heading) AS pkgCnt
INNER JOIN holiday_type ht
ON pkgCnt.holiday_type_id = ht.holiday_type_id
WHERE pkg.package_heading = pkgCnt.package_heading
GROUP BY pkg.holiday_type_id
ORDER BY pkg.holiday_type_id;
答案 1 :(得分:0)
感谢@pratik garg,我设法找到了我想要的解决方案。请在下面找到最终的SQL:
SELECT pkgCnt.holiday_type_desc,
CASE
WHEN SYSDATE() <= pkg.end_date THEN
COUNT(DISTINCT pkgCnt.package_heading)
ELSE
0
END count
FROM package pkg,
(
SELECT pkg.holiday_type_id, holiday_type_desc, package_heading
FROM package pkg
INNER JOIN holiday_type ht
ON pkg.holiday_type_id = ht.holiday_type_id
GROUP BY pkg.holiday_type_id, package_heading
) AS pkgCnt INNER JOIN holiday_type ht ON pkgCnt.holiday_type_id = ht.holiday_type_id
WHERE pkg.package_heading = pkgCnt.package_heading
GROUP BY pkg.holiday_type_id
ORDER BY pkg.holiday_type_id;