简体   繁体   中英

Changing a Select Query to a Count Distinct Query

I am using a Select query to select Members, a variable that serves as a unique identifier, and transaction date, a Date format (MM/DD/YYYY).

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

My ultimate aim is to count the # of unique members by month (ie, a unique member in day 3, 6, 12 of a month is only counted once). I don't want to select any data, but rather run this calculation (count distinct by month) and output the calculation.

This will give distinct count per month.

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

So for this input

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

You will get this output

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

You might want to try this. This might work.

SELECT REPLACE(CONVERT(DATE,transaction_date,101),'-','/') AS [DATE],
COUNT(MEMBERS) AS [NO OF MEMBERS]
FROM BAR
WHERE REPLACE(CONVERT(DATE,transaction_date,101),'-','/') IN
(
SELECT REPLACE(CONVERT(DATE,transaction_date,101),'-','/')
FROM BAR
)
GROUP BY REPLACE(CONVERT(DATE,transaction_date,101),'-','/')
ORDER BY REPLACE(CONVERT(DATE,transaction_date,101),'-','/')

Use COUNT(DISTINCT members) and date_trunc('month', transaction_date) to retain timestamps for most calculations (and this can also help with ordering the result). to_char() can then be used to control the display format but it isn't required elsewhere.

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)
;

result sample:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM