在“选择查询”中添加ORDER BY时出错

时间:2014-09-26 05:26:22

标签: sql postgresql sql-order-by distinct

select 
    distinct on (productid)p.product,
    pb.productid, 
    pb.mrp,
    pb.ptr,
    pb.ssr,
    pt.patent
from  prod_batch pb
    inner Join  prod_patent pt using(patentid) 
    inner Join  prods p using(productid)  
where(qty - iqty) > 0 

这会选择正确返回并获得我想要的内容。!在上面的中添加ORDER BY选择以根据product&进行排序#39; s名字我曾经这样写过..

select 
    distinct on (productid)p.product,
    pb.productid, 
    pb.mrp,
    pb.ptr,
    pb.ssr,
    pt.patent
from  prod_batch pb
    inner Join  prod_patent pt using(patentid) 
    inner Join  prods p using(productid)  
where(qty - iqty) > 0 
order by 
    product -- this is my column name to order by 

执行此操作时出错

  

错误:SELECT DISTINCT ON表达式必须与初始ORDER BY匹配   表达式

3 个答案:

答案 0 :(得分:0)

您可以尝试这样

选择 - 1

select * from (
select 
    distinct on (productid)p.product,
    pb.productid, 
    pb.mrp,
    pb.ptr,
    pb.ssr,
    pt.patent
from  prod_batch pb
    inner Join  prod_patent pt using(patentid) 
    inner Join  prods p using(productid)  
where(qty - iqty) > 0 
order by 
    product
) t order by product

选择 - 2

With cte as (
select 
        distinct on (productid)p.product,
        pb.productid, 
        pb.mrp,
        pb.ptr,
        pb.ssr,
        pt.patent
    from  prod_batch pb
        inner Join  prod_patent pt using(patentid) 
        inner Join  prods p using(productid)  
    where(qty - iqty) > 0 

) select * from cte order by product

选择 - 3

只需将您的选择放入视图

create or replace view pro_details as 
select 
    distinct on (productid)p.product,
    pb.productid, 
    pb.mrp,
    pb.ptr,
    pb.ssr,
    pt.patent
from  prod_batch pb
    inner Join  prod_patent pt using(patentid) 
    inner Join  prods p using(productid)  
where(qty - iqty) > 0 

用法:select * from pro_details order by product

答案 1 :(得分:0)

DISTINCT ON(expression [,...])仅保留给定表达式求值的每组行的第一行。 [...]注意"第一行"除非使用ORDER BY确保首先出现所需的行,否则每个集合都是不可预测的。 [...] DISTINCT ON表达式必须与最左边的ORDER BY表达式匹配。

尝试以下

select 
     distinct on (productid)p.product,
     pb.productid, 
     pb.mrp,
     pb.ptr,
     pb.ssr,
     pt.patent
from  prod_batch pb
inner Join  prod_patent pt using(patentid) 
inner Join  prods p using(productid)  
where(qty - iqty) > 0 
order by 
     p.productid,p.product

答案 2 :(得分:0)

add table aliase with field "product"

select 
    distinct on (productid)p.product,
    pb.productid, 
    pb.mrp,
    pb.ptr,
    pb.ssr,
    pt.patent
from  prod_batch pb
    inner Join  prod_patent pt using(patentid) 
    inner Join  prods p using(productid)  
where(qty - iqty) > 0 
order by 
    p.product