1

我有两张桌子:

table1        table2
column id     column id   column value
1             1           count_20
2             1           count_30
3             2           count_20
4             2           count_50
...           2           count_200
              3           count_30
              3           count_50
              3           count_200
              4           count_130
              ...         ...

我想构建一个查询,该查询将从中选择每一行table1, column idMAX从相应的column valuefrom中选择值,并在列 中table2做一个DESC短的。intvalue

所以输出应该是:

table1.id     value
2             count_200  
3             count_200  
4             count_130  
1             count_30  
...           ...  

我已经尝试过了JOIN,但是对于每一个我从.value (count_%)table2idtable1

SELECT table1.id, table2.id, table2.value FROM table1
LEFT JOIN table2
ON table2.id=table1.id
WHERE table1.id<'100'
ORDER BY
CASE value
  WHEN 'count_20' THEN '20' 
END DESC,
CASE value
  WHEN 'count_30' THEN '30' 
END DESC,
CASE value
  WHEN 'count_50' THEN '50' 
END DESC,
CASE value
  WHEN 'count_130' THEN '130' 
END DESC,
CASE value
  WHEN 'count_200' THEN '200' 
END DESC;

输出:

table1.id   table2.id   value
2           2           count_200  
3           3           count_200  
4           4           count_130  
2           2           count_50  
3           3           count_50  
1           1           count_30  
3           3           count_30  
1           1           count_20  
2           2           count_20  
...         ...  

任何帮助,将不胜感激。

4

2 回答 2

1

试试这个:

select t2.id, 
'count_' + cast(max(cast(replace(t2.value, 'count_', '') as int)) varchar) intValue
from table1 t1
join table2 t2 on t1.id = t2.id
group by t2.id
order by max(cast(replace(t2.value, 'count_', '') as int)) desc

这导致:

+----+------------+
| 身份证 | 价值 |
+----+------------+
| 2 | count_200 |
| 3 | count_200 |
| 4 | count_130 |
| 1 | count_30 |
+----+------------+

在这里拉小提琴。

于 2012-04-22T02:37:15.597 回答
0

http://www.w3schools.com/sql/sql_distinct.asp 看看这个。这只会显示一次值。

于 2012-04-22T01:33:29.963 回答