【问题标题】:Changing a Select Query to a Count Distinct Query将 Select 查询更改为 Count Distinct 查询
【发布时间】:2016-05-06 15:52:02
【问题描述】:

我正在使用 Select 查询来选择成员(用作唯一标识符的变量)和交易日期(日期格式 (MM/DD/YYYY))。

Select Members , transaction_date,
FROM table WHERE Criteria = 'xxx'
Group by Members, transaction_date;

我的最终目标是按月计算唯一成员的数量(即,每月第 3、6、12 天的唯一成员只计算一次)。我不想选择任何数据,而是运行此计算(按月份不同计数)并输出计算。

【问题讨论】:

  • mysqlpostgres?
  • 使用 SQL Workbench 的 postgres
  • 如果Members 是一个唯一标识符,您为什么还要费心用它聚合任何东西?也许您应该包括样本数据和所需的结果。

标签: sql postgresql


【解决方案1】:

这将给出每月不同的计数。

SQLFiddle Demo

select month,count(*) as distinct_Count_month 
from
(
    select members,to_char(transaction_date, 'YYYY-MM') as month
    from table1
    /* add your where condition */
    group by members,to_char(transaction_date, 'YYYY-MM')
) a
group by month

所以对于这个输入

+---------+------------------+
| members | transaction_date |
+---------+------------------+
|       1 | 12/23/2015       |
|       1 | 11/23/2015       |
|       1 | 11/24/2015       |
|       2 | 11/24/2015       |
|       2 | 10/24/2015       |
+---------+------------------+

你会得到这个输出

+----------+----------------------+
|  month   | distinct_count_month |
+----------+----------------------+
| 2015-10  |                    1 |
| 2015-11  |                    2 |
| 2015-12  |                    1 |
+----------+----------------------+

【讨论】:

    【解决方案2】:

    您可能想试试这个。这可能会奏效。

    SELECT REPLACE(CONVERT(DATE,transaction_date,101),'-','/') AS [DATE],
    COUNT(MEMBERS) AS [NO OF MEMBERS]
    从酒吧
    WHERE REPLACE(CONVERT(DATE,transaction_date,101),'-','/') IN
    (
    SELECT REPLACE(CONVERT(DATE,transaction_date,101),'-','/')
    来自酒吧
    )
    GROUP BY REPLACE(CONVERT(DATE,transaction_date,101),'-','/')
    ORDER BY REPLACE(CONVERT(DATE,transaction_date,101),'-','/')

    【讨论】:

      【解决方案3】:

      使用 COUNT(DISTINCT members) 和 date_trunc('month', transaction_date) 为大多数计算保留时间戳(这也有助于对结果进行排序)。然后可以使用 to_char() 来控制显示格式,但在其他地方不需要。

      SELECT
            to_char(date_trunc('month', transaction_date), 'YYYY-MM')
          , COUNT(DISTINCT members) AS distinct_Count_month
      FROM table1
      GROUP BY
            date_trunc('month', transaction_date)
      ;
      

      结果样本:

      | to_char | distinct_count_month |
      |---------|----------------------|
      | 2015-10 |                    1 |
      | 2015-11 |                    2 |
      | 2015-12 |                    1 |
      

      见:http://sqlfiddle.com/#!15/57294/2

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-06
        • 2014-05-01
        • 1970-01-01
        相关资源
        最近更新 更多