SQL查询仅返回唯一结果

时间:2014-12-01 16:19:08

标签: sql

我有以下SQL查询正常工作...

SELECT *
FROM
    wp_rg_lead
    INNER JOIN wp_rg_lead_detail ON
            wp_rg_lead.id=wp_rg_lead_detail.lead_id
WHERE wp_rg_lead.form_id = '7'
and  cast(date_created as date) >= current_date - interval '7' day

我想将此修改为仅返回唯一记录。我遇到的问题是,每个“条目”实际上都是由几个组成的......

id  |  form_id  |  entry_id  |    value
--------------------------------------------
1        1            75          red
2        1            75          broken
3        1            75          apple
4        7            33          yellow
5        7            33          faulty
6        7            33          banana
7        7            33          ripe
8        7            22          red
9        7            22          strawberry
10       7            22          broken
11       7            22          squashed

使用上述数据我只希望它返回2个结果

1 个答案:

答案 0 :(得分:0)

这样做你想要的吗?

SELECT distinct form_id
FROM wp_rg_lead INNER JOIN
     wp_rg_lead_detail
     ON wp_rg_lead.id = wp_rg_lead_detail.lead_id
WHERE cast(date_created as date) >= current_date - interval '7' day;

如果你想要一个完整的任意行,看起来你正在使用Postgres,那么你可以使用distinct on

SELECT distinct on (form_id) *
FROM wp_rg_lead INNER JOIN
     wp_rg_lead_detail
     ON wp_rg_lead.id = wp_rg_lead_detail.lead_id
WHERE cast(date_created as date) >= current_date - interval '7' day
ORDER BY form_id, id;