来自相同 table 的查询以提取不同的数据
Query from same table to extract different data
在单个 table 中,我有 3 列。首先定义一个扇区,第二个计数和第三个数量。我需要通过以下方式提取 5 列数据。第一列扇区。第二个和第三个包含金额小于计数的值,第三个和第四个显示金额大于特定部门中的计数。我的查询应该如何显示?
示例数据 - 第一个扇区的 4 行数据。
1,23,44
1,20,15
1,50,45
1,30,20
结果应该是
1,100,80,23,44
您可以使用 GROUP BY
和 SUM()
聚合函数以及 CASE
语句(例如
)来完成它
SELECT sector,
SUM(case when count > amount then count else 0 end) as count1,
SUM(case when amount < count then amount else 0 end) as amount1,
SUM(case when count < amount then count else 0 end) as count2,
SUM(case when amount > count then amount else 0 end) as amount2
FROM mytable
GROUP BY sector;
在单个 table 中,我有 3 列。首先定义一个扇区,第二个计数和第三个数量。我需要通过以下方式提取 5 列数据。第一列扇区。第二个和第三个包含金额小于计数的值,第三个和第四个显示金额大于特定部门中的计数。我的查询应该如何显示?
示例数据 - 第一个扇区的 4 行数据。
1,23,44
1,20,15
1,50,45
1,30,20
结果应该是
1,100,80,23,44
您可以使用 GROUP BY
和 SUM()
聚合函数以及 CASE
语句(例如
SELECT sector,
SUM(case when count > amount then count else 0 end) as count1,
SUM(case when amount < count then amount else 0 end) as amount1,
SUM(case when count < amount then count else 0 end) as count2,
SUM(case when amount > count then amount else 0 end) as amount2
FROM mytable
GROUP BY sector;