0

我有表 T1:

NAME        GOODS1    .GOODS2  SERVICES
TELENOR       100        0      0
VIP           100       200     350
T-MOBILE      100       100     50

我必须只在两列中得到结果:

GOODS      60
SERVICES   40

所以结果是:在第一列中始终作为 GOODS 和 SERVICES 的值(如何将它们作为数据?)在第二列中计算总和的百分比:

where SUM(GOODS)=SUM(GOODS1+GOODS2)

sum(SERVICES)=sum(SERVICES)

所以总金额是1000
货是600(100+100+200+100+100)。(所以它是 1000 的 60%)
服务是350+50=400- 所以它是 1000 的 40%。

另外如何进行此计算?
非常感谢你!!!!

4

4 回答 4

2
SELECT 
  'GOODS' AS Name, 
  (SUM(Goods1) + SUM(Goods2)) / (SUM(Goods1) + SUM(Goods2) + SUM(Services)) * 100 AS Total
FROM T1
UNION ALL
SELECT 
  'SERVICES' AS Name, 
  SUM(Services) / (SUM(Goods1) + SUM(Goods2) + SUM(Services)) * 100 AS Total
FROM T1

这会给你:

NAME        TOTAL
GOODS       60
SERVICES    40
于 2013-01-13T19:14:56.033 回答
0

您是否期望总产量为 1000,商品总数为 600,服务总数为 400。

如果是这样,试试这个:

SELECT 
  SUM(Goods1) + SUM(Goods2) + SUM(Services) as OverallTotal,
  SUM(Goods1) + SUM(Goods2) as GoodsTotal,
  SUM(Services) as ServicesTotal
FROM T1

还有SQL 小提琴

-编辑

如果您正在考虑将它们作为 2 个不同的行,您可以尝试UNION

SELECT 100*GoodsTotal/OverallTotal
FROM (
SELECT 
  SUM(Goods1) + SUM(Goods2) + SUM(Services) as OverallTotal,
  SUM(Goods1) + SUM(Goods2) as GoodsTotal,
  SUM(Services) as ServicesTotal
FROM T1) AS T
UNION
SELECT 100*ServicesTotal/OverallTotal 
FROM (
SELECT 
  SUM(Goods1) + SUM(Goods2) + SUM(Services) as OverallTotal,
  SUM(Goods1) + SUM(Goods2) as GoodsTotal,
  SUM(Services) as ServicesTotal
FROM T1) AS T

还有SQL 小提琴。祝你好运。

于 2013-01-13T19:09:38.847 回答
0
SELECT
    ((TotalGoods * 100)/ Total) as TotalPercentGoods,
    ((TotalServices * 100) / Total) as TotalPercentServices
FROM 
(
    SELECT 
        SUM(Goods1)+SUM(Goods2)+SUM(SERVICES) as Total,
        SUM(Goods1)+SUM(Goods2) as TotalGoods,
        SUM(Services) as TotalServices
    FROM T1 
) as l

演示

于 2013-01-13T19:12:20.860 回答
0

这是一种不同的方法:

select c.which,
       sum(case when which = 'GOODS' then Goods1 + GOod2
                else Services
           end) / sum(Goods1+Goods2+Services)*100
from table 1 cross join
     (select 'GOODS' as which union all select 'SERVICES' end) c

这应该只需要扫描表一次。

于 2013-01-13T19:34:45.690 回答