通过基于某个id连接相同的表行来获取数据

时间:2017-05-24 04:52:58

标签: mysql sql database hql

我有一张桌子

enter image description here

我要将行提取为areaarea_namecity_size1 ratecity_size2 ratecity_size3基于rate

area分组

enter image description here

最好的方法是什么

2 个答案:

答案 0 :(得分:0)

如果只有3个不同的city_size,你可以像下面这样做。 假设同一AREA_NAME area也相同。

select area,area_name
,max(case when city_size=1 
        then rate 
        else null end
    ) as city_size_1_rate
,max(case when city_size=2 
        then rate 
        else null end
    ) as city_size_2_rate
,max(case when city_size=3 
        then rate 
        else null end
    ) as city_size_3_rate   
from your_table
group by area,area_name;    

说明:case when city_size=1 then rate else null end只会ratecity_size=1提供null,但它会为您提供group by。当您area max并选择rate或更高价值时,您将只获得非空city_size_1_rate,即 private async void btnProcessFIle_Click(object sender, EventArgs e) { var task = Task.Run(() => { var count = countCharacters(); lblCount.BeginInvoke((Action) (() => { lblCount.Text = "No. of characters in file=" +Environment.NewLine+ count.ToString(); })); }); await task; } 。同样适用于其他2列。

答案 1 :(得分:0)

你应该在这里使用分组

SELECT area,area_name,city_size1 rate,city_size2 rate,city_size3 rate FROM your_table_name GROUP BY area;

group by可以执行:

  • 扫描整个表格,将area的每个值存储在a中 哈希表
  • 返回哈希表的键

如此优化速度,但可能需要大量内存。