如何建立一个表格,其中每一列都会有条件?

时间:2019-05-07 23:55:45

标签: sql postgresql

我正在Rapid 7的Insight VM中构建SQL查询。该方案用here表示。

我正在尝试获得如下结果:

                           tv  |  tv_1m   |
-------------------------------------------
asset_importance_HIGH   |  #   |    #     |
-------------------------------------------
asset_importance_Med    |  #   |    #     |
-------------------------------------------
asset_importance_Low    |  #   |    #     |

此表显示按重要性和每个重要性的漏洞总数以及上个月发布的漏洞分组的所有资产。重要性就像资产的关键程度。

这是我遇到的使我接近的查询,但并不是我真正需要的:

SELECT num.importance, COUNT(num.vulnerability_id), 'All' as MyTag
FROM (
   SELECT dv.vulnerability_id, importance, dv.date_published
   FROM dim_site ds
      JOIN dim_site_asset dsa USING (site_id)
      JOIN fact_asset_vulnerability_instance favi USING (asset_id)
      JOIN dim_vulnerability dv USING (vulnerability_id)

   WHERE ds.name NOT LIKE '_Test%'

   GROUP BY asset_id, dv.vulnerability_id, ds.importance, dv.date_published
   ORDER BY asset_id, dv.vulnerability_id
) num

GROUP BY num.importance

UNION

SELECT num.importance, COUNT(num.vulnerability_id), '30d' as MyTag
FROM (
   SELECT dv.vulnerability_id, importance, dv.date_published
   FROM dim_site ds
      JOIN dim_site_asset dsa USING (site_id)
      JOIN fact_asset_vulnerability_instance favi USING (asset_id)
      JOIN dim_vulnerability dv USING (vulnerability_id)

   WHERE ds.name NOT LIKE '_Test%' AND dv.date_published > (SELECT date_trunc('MONTH',now())::DATE - 30)

   GROUP BY asset_id, dv.vulnerability_id, ds.importance, dv.date_published
   ORDER BY asset_id, dv.vulnerability_id
) num

GROUP BY num.importance

哪个给我:

                           count  |  myTag     |
------------------------------------------------
asset_importance_HIGH   |    #    |    30d     |
------------------------------------------------
asset_importance_Med    |    #    |    30d     |
------------------------------------------------
asset_importance_Low    |    #    |    30d     |
------------------------------------------------
asset_importance_HIGH   |    #    |    All     |
------------------------------------------------
asset_importance_Med    |    #    |    All     |
------------------------------------------------
asset_importance_Low    |    #    |    All     |

0 个答案:

没有答案