-1

我正在尝试创建一个带有查询查询的图表,但无论我尝试什么,都会收到 500 错误。我最终将 cfchart 标记的范围缩小为问题,但在其中找不到任何语法错误,也没有任何逻辑错误。

<cfquery name="getData" datasource="#dsn#">
   SELECT 
          ( SELECT Count(UserID) 
            FROM   Users 
            WHERE  StripeCustomerID IS NOT NULL
          ) AS 'Licenses'
          , COUNT(UserID) AS 'Registrations'
          , UserID AS 'User'
  FROM  Users
  WHERE DATEDIFF(hour, FirstContact, DateStamp) <= '12'
  GROUP BY UserID
</cfquery>

<cfquery name="queryOfQuery" dbtype="query">
   SELECT (Licenses/Registrations) AS Percent FROM getData
</cfquery>


<cfchart format="flash"> 
     <cfchartseries type="bar"
        query="queryOfQuery"
        itemcolumn="UserID"
        valuecolumn="Percent"  />
</cfchart>

样本数据

Users Table Sample Data
UserID    StripeCustomerID
35         cus_8LOSlmvEQcfg1g
36         cus_6ixCBe7aU1MJEt
50         NULL
60         cus_6ifLCNmR9rOBCl
69         NULL
70         NULL
72         NULL
73         NULL
74         NULL  
4

1 回答 1

2

你的语法问题是

SELECT (Licenses/Registrations) AS Percent FROM getData

百分比是保留关键字,因此您需要添加方括号或单引号,以让 SQL 引擎知道您正在使用保留关键字作为列别名。

SELECT (Licenses/Registrations) AS [Percent] FROM getData

或者

SELECT (Licenses/Registrations) AS 'Percent' FROM getData

您可以轻松地将百分比列添加到原始数据集中。

SELECT 
    (SELECT Count(UserID) FROM Users WHERE StripeCustomerID IS NOT NULL)     AS     Licenses, 
    COUNT(UserID) AS Registrations,
    (SELECT Count(UserID) FROM Users WHERE StripeCustomerID IS NOT NULL) / COUNT(UserID) AS [Percent],
    UserID AS User
FROM Users
WHERE DATEDIFF(hour, FirstContact, DateStamp) <= '12'
GROUP BY UserID

另外,我很好奇您想要什么许可证。你是想得到DISTINCT UserId count还是count全部non null UserIds。你的查询的其余部分表明USerId它在用户表中重复(我觉得这很奇怪)......所以UserId5 可能存在 2 或 3 次,所以计算 distinct 会给你 1 用户 ID 5 而不添加 distinct 会给你2个或3个...

registrations总是?1_ 如果是这样,那么UserId它是独一无二的,您根本不需要在主查询中进行聚合。百分比的答案将始终与 1/# of Licenses 相同......

根据您的评论,这似乎是您想要的查询。

SELECT
    COUNT(UserId) AS Registrations
    ,SUM(CASE WHEN StripeCustomerId IS NOT NULL THEN 1 ELSE 0 END) AS Licenses
    ,CASE
       WHEN SUM(CASE WHEN StripeCustomerId IS NOT NULL THEN 1 ELSE 0 END) = 0 THEN 0
       ELSE COUNT(UserId) / SUM(CASE WHEN StripeCustomerId IS NOT NULL THEN 1 ELSE 0 END)
    END AS [Percent]
FROM
    Users
WHERE DATEDIFF(hour, FirstContact, DateStamp) <= '12'
于 2016-06-29T16:24:48.117 回答