两个group by和求和sql的总数的百分比

时间:2018-09-07 03:02:06

标签: sql postgresql percentage

我有一个如下表:

id     Category     Spend
------------------------------
00001    Apple       10
00001    Oranges     4
00001    Apple       21
00001    Oranges     50
00002    Oranges     32
00002    Apple       2
00002    Oranges     31
Etc.

我正在寻找一个可以显示以下内容的表

id     Category     Spend_Ratio
------------------------------
00001    Apple       36%
00001    Oranges     64%
00002    Apple       3%
00001    Oranges     97%

逻辑是根据ID进行的类别支出分组来产生比率。

我已经设法做到了这一点:

SELECT id, category, SUM(spend)
FROM table
GROUP BY id, category;

完全迷失了下一步。

2 个答案:

答案 0 :(得分:0)

您可以使用此:

WITH sum_category AS 
(
    SELECT id, category,
        SUM(spend) AS spend
    FROM table_name
    GROUP BY id, category
)
SELECT id, category,
    ROUND(100 * spend / SUM(spend) OVER (PARTITION BY id)) AS spend_ratio
FROM sum_category
ORDER BY id, category;

尝试SqLFiddle

答案 1 :(得分:0)

使用窗口功能:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
    return 22
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
    identifiers = ["Adana","Ankara","Antalya","Balikesir","Bursa","Denizli","Diyarbakir","Eskisehir","Gaziantep","Hatay","Icel","Istanbul","Izmir","Kayseri","Kocaeli","Konya","Manisa","Sakarya","Samsun","Sivas","Trabzon","Sanliurfa"]
    //let cell = tableView.dequeueReusableCell(withIdentifier: "CellTwo")
    //cell?.textLabel!.text = identifiers[indexPath.row]
    //return cell!
    let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "CellTwo")
    cell.textLabel!.text = identifiers[indexPath.row]
    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){


    // here you can use someThing like an array of your segue identifiers
    selectedParamTwo = tableView.cellForRow(at: indexPath)!.textLabel!.text!
    self.performSegue(withIdentifier: "seg2", sender: self)

}

这会产生一个介于0和1之间的数字。我不确定您是否真的想将数字格式化为百分比。