如何在同一列中相乘 sql
How to multiply in the same column sql
我有一个 table 三列 Locations,Count Location,Table 来自。我如何乘以 (Count Location) 然后除以它以获得百分比。
示例:尝试划分同一列中的两个位置!然后乘以 100 (Count Location / Count Location)*100
Atlanta, GA 6 CL Table
Atlanta, GA 20 TW Table
The result (6/20)*100=30%
|Location |Count Location| Table From|
-------------------------------------------
Atlanta, GA 6 CL Table
Atlanta, GA 20 TW Table
Austin, TX 27 TW Table
Austin, TX 5 CL Table
Chicago, IL 6 CL Table
Chicago, IL 19 TW Table
Corona, CA 6 CL Table
Corona, CA 50 TW Table
Dallas, TX 37 TW Table
Dallas, TX 3 CL Table
Denver, CO 3 CL Table
Denver, CO 19 TW Table
Houston, TX 21 TW Table
Houston, TX 11 CL Table
是否有办法对所有位置执行此操作并在它们旁边的新列中显示结果?还是我需要制作一个新的 table 以使其更容易?
好的,我明白了。你想要 TW 的 CL 百分比。您可以使用 window 函数执行此操作:
select t.*,
(100 * max(case when tablefrom = 'CL Table' then count end) over (partition by location)/
max(case when tablefrom = 'TW table' then count end) over (partition by location)
) as percentage
from table t;
如果您只想要每个位置的结果(这对我来说更有意义),只需使用聚合:
select location,
(100 * max(case when tablefrom = 'CL Table' then count end) /
max(case when tablefrom = 'TW table' then count end)
) as percentage
from table t
group by location
我有一个 table 三列 Locations,Count Location,Table 来自。我如何乘以 (Count Location) 然后除以它以获得百分比。
示例:尝试划分同一列中的两个位置!然后乘以 100 (Count Location / Count Location)*100
Atlanta, GA 6 CL Table
Atlanta, GA 20 TW Table
The result (6/20)*100=30%
|Location |Count Location| Table From|
-------------------------------------------
Atlanta, GA 6 CL Table
Atlanta, GA 20 TW Table
Austin, TX 27 TW Table
Austin, TX 5 CL Table
Chicago, IL 6 CL Table
Chicago, IL 19 TW Table
Corona, CA 6 CL Table
Corona, CA 50 TW Table
Dallas, TX 37 TW Table
Dallas, TX 3 CL Table
Denver, CO 3 CL Table
Denver, CO 19 TW Table
Houston, TX 21 TW Table
Houston, TX 11 CL Table
是否有办法对所有位置执行此操作并在它们旁边的新列中显示结果?还是我需要制作一个新的 table 以使其更容易?
好的,我明白了。你想要 TW 的 CL 百分比。您可以使用 window 函数执行此操作:
select t.*,
(100 * max(case when tablefrom = 'CL Table' then count end) over (partition by location)/
max(case when tablefrom = 'TW table' then count end) over (partition by location)
) as percentage
from table t;
如果您只想要每个位置的结果(这对我来说更有意义),只需使用聚合:
select location,
(100 * max(case when tablefrom = 'CL Table' then count end) /
max(case when tablefrom = 'TW table' then count end)
) as percentage
from table t
group by location