我目前的声明如下:
SELECT
SUM(claims.sanctioned_resultant) AS 'Resultant',
SUM(claims.sanctioned_flooring) AS 'Flooring',
SUM(claims.sanctioned_contents) AS 'Furniture',
等等,我需要包含一个" WHERE"以某种方式。沿着:
SUM(claims.sanctioned_resultant WHERE claims.a_column = 1)
显然这不起作用,因为SUM只是总和。我目前使用WHERE claims_a_column = 1
子句进行了另一个查询,然后将结果合并。 " WHERE"条件无法添加到此查询中,因为大多数结果都不会被它选中。
我已经查看过CASE WHEN和子选项,但无法弄清楚实际的语法。
完整查询,如果有帮助:
SELECT
CONCAT(users.user_first_name,IF((users.user_surname<>''),CONCAT(' ',users.user_surname),'')) as 'Surveyor',
SUM(claims.sanctioned_roof + claims.sanctioned_building + claims.sanctioned_internal + claims.sanctioned_resultant + claims.sanctioned_flooring + claims.sanctioned_contents) AS 'Overall',
SUM(claims.sanctioned_roof) AS 'Roofing',
SUM(claims.sanctioned_building + claims.sanctioned_internal) AS 'Building',
SUM(claims.sanctioned_resultant) AS 'Resultant',
SUM(claims.sanctioned_flooring) AS 'Flooring',
SUM(claims.sanctioned_contents) AS 'Furniture',
COUNT(CASE WHEN claims.claimed_amount > 0 THEN 1 END) AS 'OverallCount',
COUNT(CASE WHEN (claims.claimed_amount > 0 AND claims.peril_id IN (" . implode(',', $WRPPerils) . ")) THEN 1 END) AS 'WRPCount',
COUNT(CASE WHEN claims.claimed_roof > 0 THEN 1 END) AS 'RoofingCount',
COUNT(CASE WHEN (claims.claimed_building > 0) OR (claims.sanctioned_internal > 0) THEN 1 END) AS 'BuildingCount',
COUNT(CASE WHEN claims.claimed_resultant > 0 THEN 1 END) AS 'ResultantCount',
COUNT(CASE WHEN claims.claimed_flooring > 0 THEN 1 END) AS 'FlooringCount',
COUNT(CASE WHEN claims.claimed_contents > 0 THEN 1 END) AS 'FurnitureCount',
COUNT(CASE WHEN claims.claimed_amount > 0 AND claims.letter_of_findings = 'Y' THEN 1 END) AS 'LOFCount'
FROM
claims claims
INNER JOIN users users ON claims.surveyor_id = users.user_id
INNER JOIN insurers insurers on claims.insurer_id = insurers.insurer_id
WHERE
(claims.claim_type <> " . $conn->qstr(TYPE_DESKTOP) . ") AND
(claims.claim_type <> " . $conn->qstr(TYPE_AUDIT) . ") AND
(claims.claim_cancelled_id <= 0) AND
(claims.date_completed BETWEEN '" . $start_date . " 00:00:00' AND '" . $end_date . " 23:59:59') AND
(claims.overturn_confirmed = 'N' OR claims.overturn_confirmed IS NULL)
GROUP BY surveyor_id
答案 0 :(得分:3)
我认为最简单的方法就是在SUM函数本身中使用CASE语句,如下所示:
SUM(CASE WHEN claims.a_column = 1 THEN claims.sanctioned_resultant ELSE 0 END)