0

我怎么写这个..我有一个表“公司”,有一列“大小”。大小引用枚举。当“大小”列是:

1 = 15
2 = 30
3 = 50
4 = 100
5 = 250

换句话说,我的表格将公司规模显示为 1、2、3、4 或 5。而 1 实际上是公司规模 15。

这是更大查询的一部分:

SELECT COUNT(DISTINCT(ID)) AS 'Total # of Opps', AVG(Size*?) AS 'AverageEstimatedCompanySize'
FROM persontable AS POJT INNER JOIN opportunity
ON POJT.ID = opportunity.id
WHERE opportunity.TimeStamp >= '2012-01-01' AND opportunity.TimeStamp <= '2012-12-31' AND POJT.JobTitleID IN 
    (SELECT Id
    FROM job
    WHERE CategoryID IN 
        (SELECT id
        FROM job_category
        WHERE name IN ('Sc', 'Ma', 'Co', 'En', 'Tr')))
4

2 回答 2

0

听起来像是可以用case statement解决的事情。以下内容未经测试,但应为您指明正确的方向。

SELECT 
    COUNT(DISTINCT(ID)) AS 'Total # of Opps', 
    AVG(
        CASE Size
            WHEN 1 THEN 15
            WHEN 2 THEN 30
            WHEN 3 THEN 50
            WHEN 4 THEN 100
            WHEN 5 THEN 250
        END
    ) AS 'AverageEstimatedCompanySize'
FROM persontable AS POJT INNER JOIN opportunity
ON POJT.ID = opportunity.id
WHERE opportunity.TimeStamp >= '2012-01-01' AND opportunity.TimeStamp <= '2012-12-31' AND POJT.JobTitleID IN 
    (SELECT Id
    FROM job
    WHERE CategoryID IN 
        (SELECT id
        FROM job_category
        WHERE name IN ('Sc', 'Ma', 'Co', 'En', 'Tr')))
于 2013-09-19T18:38:13.003 回答
0

我认为一种方法可能是将查询适当地修改为JOINCompany(这是您需要解决的问题),然后修改AVG语句:

... AVG(CASE `Size`
        WHEN 1 THEN 15
        WHEN 2 THEN 30
        WHEN 3 THEN 50
        WHEN 4 THEN 100
        WHEN 5 THEN 250 END) AS 'AverageEstimatedCompanySize'

哪里Size是从Company表。

现在,一种更动态的方法是创建一个新字段,甚至是一个新表,映射这些大小和表,然后JOINCompany查询中说新表,然后每行获取适当的字段。那将摆脱CASE声明。

于 2013-09-19T18:38:24.523 回答