如何在没有group by子句错误的情况下嵌套这些SQL语句?

时间:2013-08-07 19:13:27

标签: sql sql-server

我正在尝试查询具有这些参数的数据库:

交易日期,用户电子邮件地址

我所做的就是使用此查询:

SELECT [User Email Address],  COUNT(*) AS 'count'
    FROM
      [DATABASE].[TABLE]
    GROUP BY [User Email Address]

显示带有参数的表格:

电子邮件地址,计数

在这种情况下,count列显示原始表中用户电子邮件的出现次数。

我接下来要做的是查看截至今天的去年的交易日期列,并将该子集的计数列与原始的计数列(可追溯到3年)进行比较。具体来说,我希望我的最终结果表是:

用户用户电子邮件地址,countDiff

其中countDiff是一年子集和原始子集的计数差异。

我试过了:

SELECT [User Email Address], [Transaction Date], [count - COUNT(*)] AS 'countdDifference'

FROM (

    SELECT [User Email Address],  COUNT(*) AS 'count'
    FROM
      [DATABASE].[TABLE]
    GROUP BY [User Email Address]


) a

WHERE a.[Transaction Date] >= '2011-08-07 00:00:00.000'


ORDER BY [count] DESC

但是我得到[Transaction Date]不在Group By子句或聚合中的错误。如果我把它放在[User Email Address]旁边的Group By中,它会弄乱数据。

这实际上是我遇到的一个常见问题。有什么方法可以绕过这个吗?

4 个答案:

答案 0 :(得分:3)

您需要使用两个不同的子查询:一个计算完整条目,另一个计算去年的条目。

也许这会对你有所帮助:

SELECT a.*, a.[count] - Coalesce(b.[count], 0) as 'countDif' 
FROM 
    (
        SELECT [User Email Address],  COUNT(*) AS 'count'
        FROM [DATABASE].[TABLE]
        GROUP BY [User Email Address]
    ) AS a
    LEFT JOIN (
        SELECT [User Email Address],  COUNT(*) AS 'count'
        FROM [DATABASE].[TABLE]
        WHERE [Transaction Date] >= '2011-08-07 00:00:00.000'
        GROUP BY [User Email Address]
    ) AS b ON a.[User Email Address] = b.[User Email Address]

答案 1 :(得分:2)

您可以在一个SELECT中执行两个计数:

SELECT [User Email Address],  
    SUM(CASE WHEN [Transaction Date] >= '2011-08-07' THEN 1 ELSE 0 END) AS 'FilteredCount',
    COUNT(*) AS 'TotalCount',
    COUNT(*) 
       - SUM(CASE WHEN [Transaction Date] >= '2011-08-07' THEN 1 ELSE 0 END)
         AS 'CountDifference'
    FROM
      [DATABASE].[TABLE]
    GROUP BY [User Email Address]

答案 2 :(得分:2)

您可以使用:

SELECT [User Email Address], 
       [Transaction Date], 
       count1.count - isnull(count2.count,0) as  [countdDifference]
FROM    (SELECT [User Email Address],  COUNT(*) AS 'count'
        FROM    [DATABASE].[TABLE] t1
        GROUP BY t1.[User Email Address]) as count1
LEFT JOIN (SELECT [User Email Address],  COUNT(*) AS 'count'
        FROM    [DATABASE].[TABLE] t2
        GROUP BY [User Email Address] 
        WHERE t2.[Transaction Date] >= '2011-08-07 00:00:00.000') as count2
ON      count2.[User Email Address] = count1.[User Email Address]
ORDER BY 3 DESC

你也应该开始考虑1.)不使用count,因为它使用了一堆(它几乎是reserved word但不完全); 2.)不要在你的字段名称中使用空格; 3.)找到一种易于阅读的方式来组织SQL:)

答案 3 :(得分:1)

,这样的事情怎么样?

SELECT
    [User Email Address],
    count(*) AS Total,
    sum(CASE 
            WHEN [Transaction Date] >= '2011/08/07 00:00:00.000' THEN 1
            ELSE 0 
         END) AS WithinDateRange,
    count(*) 
        - sum(CASE 
                  WHEN [Transaction Date] >= '2011/08/07 00:00:00.000' THEN 1
                  ELSE 0 
              END) AS Difference.
FROM [DATABASE].[TABLE]
GROUP BY [User Email Address]