我试图从表中找出不到10%的收入帐户。下面是表快照。基本上,我想在表格中添加Revenue mix列。
ACCOUTS REVENUE REVENUEMIX
ACCOUNT1 100 2%
ACCOUNT2 200 4%
ACCOUNT3 500 9%
ACCOUNT4 1000 19%
ACCOUNT5 1500 28%
ACCOUNT6 2000 38%
TOTAL 5300 100%
答案 0 :(得分:4)
DECLARE @P INT;
SET @P = 10;
WITH CTE AS
(
SELECT ACCOUNTS,
REVENUE,
CAST(REVENUE AS DECIMAL(5,0))/(SUM(REVENUE) OVER())*100 REVENUEMIX
FROM dbo.YourTable
)
SELECT *
FROM CTE
WHERE REVENUEMIX < @P;
Here is a sqlfiddle及其演示。我得到的样本数据的结果是:
╔══════════╦═════════╦═════════════╗
║ ACCOUNTS ║ REVENUE ║ REVENUEMIX ║
╠══════════╬═════════╬═════════════╣
║ ACCOUNT1 ║ 100 ║ 1.886792452 ║
║ ACCOUNT2 ║ 200 ║ 3.773584905 ║
║ ACCOUNT3 ║ 500 ║ 9.433962264 ║
╚══════════╩═════════╩═════════════╝
答案 1 :(得分:0)
尝试REPLACE() and CAST()
SELECT *
FROM tab_1 where cast(Replace(REVENUEMIX,'%','') as decimal(10,4))<10
答案 2 :(得分:0)
如果我正确地阅读了问题,您是否希望将示例表中显示的RevenueMix列包含在仅包含Account and Revenue的表中?这样的事情应该有效:
create table #table (
account nvarchar(10),
revenue int
)
insert #table values
('ACCOUNT1', 100 ),
('ACCOUNT2', 200 ),
('ACCOUNT3', 500 ),
('ACCOUNT4', 1000 ),
('ACCOUNT5', 1500 ),
('ACCOUNT6', 2000 )
declare @TotalRevenue int
declare @MinimumRevenueMix numeric(8,2) = 10.0
select @TotalRevenue = SUM(Revenue) from #table
select a.account,
a.revenue,
convert(nvarchar(20), a.RevenueMix) + '%' RevenueMix
from (
select account,
revenue,
convert(numeric(8,2), convert(float, revenue) / convert(float, @TotalRevenue)) * 100 RevenueMix
from #table
) a
where
a.RevenueMix < @MinimumRevenueMix
drop table #table