sql查询,当字段匹配时按值排序

时间:2018-12-13 19:49:08

标签: sql sql-order-by

我的数据如下:

data_id   name            value
-----------------------------------------
1        Address123       my street
1        Order-Date        12/23/2018 
1        firstName        Joe    
2        Address          345 other street
2        Order-Date        12/31/2018
2        firstName        Peter

...等等。

如何编写查询以使用ID作为组返回由“ OrderDate”排序的数据

例如

SELECT * 
FROM wp_cf7_data_entry 
WHERE cf7_id = 7 
AND data_id IN (SELECT * 
                FROM (
                  SELECT data_id 
                  FROM wp_cf7_data_entry 
                  WHERE 1 = 1 
                   AND cf7_id = 7 
                  GROUP BY data_id 
                  ORDER BY case 
                               when name = 'order-date' THEN 'value' 
                           end DESC,'data_id') 

基本上我想使用子查询作为订单,因此结果按Order-Date排序。

2 个答案:

答案 0 :(得分:0)

我猜您想使用conditional aggregation

select id, 
       max(case when name_field = 'OrderDate' then value end) as OrderDate,
       max(case when name_field = 'Address' then value end) as Address,
       max(case when name_field = 'Name' then value end) as Name
from yourtable
group by id
order by max(case when name_field = 'OrderDate' then value end)

这将为每个id创建一行,并按订购日期值订购结果。

答案 1 :(得分:0)

您不需要一个分组依据,因为我可以看到每个id都只有一个namefield作为ordereddate

    SELECT * FROM TABLE WHERE NAME_FIELD = 
   'OrderedDate' order by NAME_FIELD