在查询结果中仅出现一次的行

时间:2018-06-04 11:22:13

标签: sql postgresql

我想要在2月25日出现并且没有出现在3月6日的行。我试过这样的询问:

SELECT favfd.day, dv.title, array_to_string(array_agg(distinct "host_name"), ',') AS affected_hosts , htmltoText(dsol.fix),
count(dv.title) FROM fact_asset_vulnerability_finding_date favfd
INNER JOIN dim_vulnerability dv USING(vulnerability_id)
INNER JOIN dim_asset USING(asset_id)
INNER JOIN dim_vulnerability_solution USING(vulnerability_id)
INNER JOIN dim_solution dsol USING(solution_id)
INNER JOIN dim_solution_highest_supercedence dshs USING (solution_id)
WHERE (favfd.day='2018-02-25' OR favfd.day='2018-03-06') AND 
dsol.solution_type='PATCH' AND dshs.solution_id=dshs.superceding_solution_id
GROUP BY favfd.day, dv.title, host_name, dsol.fix
ORDER BY favfd.day, dv.title

给了我以下结果: results

我已经读过我需要添加类似" HAVING COUNT(*)= 1"但就像你在查询结果中看到的那样,我的计数列看起来很奇怪。以下是添加该行的结果: results with having

你能告诉我我做错了什么吗?

1 个答案:

答案 0 :(得分:0)

一种方法是使用runAsUser : 0子句来断言您的日期标准:

 $relatedEvents = Event::where('startDate', '>=', Carbon::now())
    ->where(function ($query) use ($event, $tags) {
        $query->where('hostedBy', $event->hostedBy);
        $query->orWhere('type', $event->hostedBy);
        $query->orWhere('category', $event->hostedBy);
        $query->orWhere('sector', $event->hostedBy);
        $query->orWhereHas('tags', function ($query) use ($tags) {
            $query->where('slug', $tags->slug);
        });
    })
    ->toSql();

我做的唯一重大更改是从HAVING子句中删除SELECT dv.title, array_to_string(array_agg(distinct "host_name"), ',') AS affected_hosts, htmltoText(dsol.fix), count(dv.title) FROM fact_asset_vulnerability_finding_date favfd INNER JOIN dim_vulnerability dv USING(vulnerability_id) INNER JOIN dim_asset USING(asset_id) INNER JOIN dim_vulnerability_solution USING(vulnerability_id) INNER JOIN dim_solution dsol USING(solution_id) INNER JOIN dim_solution_highest_supercedence dshs USING (solution_id) WHERE dsol.solution_type = 'PATCH' AND dshs.solution_id = dshs.superceding_solution_id GROUP BY dv.title, dsol.fix HAVING SUM(CASE WHEN favfd.day = '2018-02-25' THEN 1 ELSE 0 END) > 0 AND SUM(CASE WHEN favfd.day = '2018-03-06' THEN 1 ELSE 0 END) = 0 ORDER BY favfd.day, dv.title ,因为您在select子句中聚合使用此列。我添加了host_name子句来检查你的逻辑。

您应该进行的更改是使用显式连接替换隐式连接语法。将连接标准放入GROUP BY子句现在被认为是不好的做法。