我有两张桌子:
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 id
中选择每一行,从MAX
中选择相应column value
的{{1}}值并生成table2
在DESC
列中缩写为int
。
所以输出应该是:
value
我已尝试table1.id value
2 count_200
3 count_200
4 count_130
1 count_30
... ...
但是,对于JOIN
中的每个value
(count_%)
,我都会从table2
获得相应的id
。
table1
输出:
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;
任何帮助都将不胜感激。
答案 0 :(得分: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
这导致:
+----+-----------+ | ID | VALUE | +----+-----------+ | 2 | count_200 | | 3 | count_200 | | 4 | count_130 | | 1 | count_30 | +----+-----------+
小提琴here。
答案 1 :(得分:0)
http://www.w3schools.com/sql/sql_distinct.asp 看一下这个。这只会显示值。