确定事实表中的百分比

时间:2013-12-09 18:10:52

标签: sql sql-server sql-server-2008 data-warehouse fact-table

我是编程新手,无法找到答案。

我有以下维度(表格)和事实表格:

  • 客户: CustomerId HomeRegion
  • 地区: RegionId RegionName
  • MyTime: id MyHour
  • 事实表: CustomerId RegionId TimeId FactId

我的报告必须为: HomeRegion 小时 RegionName UserPercentage

EXAMPLE

如示例所示,只有3.67%的家乡 A 的人在上午9点移至 B ,依此类推。

我应该创建一个类似的。

问题是获取UserPercentage。这是我到目前为止所做的代码。

SELECT c.HomeRegion, mt.myhour as Time, r.RegionName as CurrentRegion,
(SELECT COUNT(*)
        /*number of users who move from their home 
        region to CurrentRegion at specific time*/
)/COUNT(c.CustomerId)*100 as UserPercentage
FROM dbo.FactTable ft 
inner join dbo.Customer c
    ON ft.CustomerId = c.CustomerId
inner join dbo.myTime mt
    ON ft.TimeId = mt.ID
inner join dbo.Regions r
    ON ft.RegionId = r.RegionId
WHERE mt.myhour = '09'
GROUP BY c.HomeRegion, mt.myhour, r.RegionName
ORDER BY c.HomeRegion, r.RegionName

2 个答案:

答案 0 :(得分:1)

在评论区域尝试这样的事情。

SELECT (TMP1.Count*100)/COUNT(TMP2.CustomerId) AS 'Percentage' 
FROM 
(
SELECT COUNT(*) AS 'Count' 
FROM dbo.FactTable ft 
inner join dbo.Customer c ON ft.CustomerId = c.CustomerId 
inner join dbo.Regions r ON ft.RegionId = r.RegionId 
WHERE 
r.RegionName IN ('A','B','C','D','E') AND 
c.HomeRegion IN ('A','B','C','D','E') 
) AS 'TMP1', dbo.Customer AS 'TMP2'

答案 1 :(得分:1)

使用分析功能
*无需选择或分组myHour常数
*假设一个客户应该同时位于一个区域(如果不是 - 那将更难选择)

select HomeRegion, CurrentRegion, 
count(*) / count(*) over () as overall_share,
count(*) / count(*) over (partition by HomeRegion) as homeregion_share, 
    from
    (SELECT c.HomeRegion, r.RegionName as CurrentRegion, c.CustomerId as CUST
    FROM dbo.FactTable ft 
    inner join dbo.Customer c
        ON ft.CustomerId = c.CustomerId
    inner join dbo.myTime mt
        ON ft.TimeId = mt.ID
    inner join dbo.Regions r
        ON ft.RegionId = r.RegionId
    WHERE mt.myhour = '09'
    GROUP BY c.HomeRegion, r.RegionName, c.CustomerId) uni_users
    GROUP by HomeRegion, CurrentRegion