返回的用户

时间:2017-03-29 09:48:21

标签: sql sql-server

我有[EVENT_DATE]和[USER_ID]的表格,我想知道如何统计同月回来的用户。

Table_01    
------------------------------------------- 
    EVENT_DATE          |   USER_ID
-------------------------------------------
2017-03-28 00:00:25.000 | 0006235012201
2017-03-04 23:00:00.000 | 0006235012201
2017-03-19 00:25:15.000 | 0006235012201
2017-02-03 10:00:02.000 | 0006235012202
2017-01-18 00:15:00.000 | 0006235012202
2017-03-28 11:00:15.000 | 0006235012202
2017-03-23 15:20:02.000 | 0006235012203
2017-02-18 12:00:06.000 | 0006235012203
2017-03-21 16:05:09.000 | 0006235012203

答案是2,因为用户0006235012201& 0006235012203都在同一个月内回归。

编辑:抱歉

我希望按月计算。

-----------------------
Month | Users Returned
-----------------------
01/17 | 70
02/17 | 60
03/17 | 10

这就是我所拥有的,但它不正确,因为它似乎是列出用户。

SELECT A.[USER_ID], A.[EVENT_DATE], COUNT(*)
FROM(
    SELECT [USER_ID], [EVENT_DATE], COUNT(*)
    FROM Table_01
    GROUP BY [USER_ID], [EVENT_DATE]
    HAVING COUNT(*) > 1
     ) A
GROUP BY A.[USER_ID], A.[EVENT_DATE]

Microsoft SQL Server 2016.兼容级别:SQL Server 2005(90)

5 个答案:

答案 0 :(得分:2)

select user_id
from your_table
group by user_id
having count(distinct year(event_date) * 100 + month(event_date)) > 1

答案 1 :(得分:0)

使用此功能可以获得月度结果

 select month(EVENT_DATE),year(EVENT_DATE), USER_ID from tableName
 where  year(EVENT_DATE)=2017
 Group by USER_ID,year(EVENT_DATE),month(EVENT_DATE)
 Having HAVING  COUNT(*) > 1

如果你想要一些具体的月份,你可以添加像月份(EVENT_DATE)= 3

这样的条件

答案 2 :(得分:0)

尝试以下脚本

SELECT  DISTINCT USER_ID
FROM    Table_01
GROUP BY USER_ID, (YEAR(EVENT_DATE)*100)+MONTH(EVENT_DATE)
HAVING  COUNT(*) > 1

答案 3 :(得分:0)

使用以下查询来获取同月返回的用户

SELECT USER_ID
FROM #Table 
GROUP BY USER_ID,(YEAR(EVENT_DATE)*100)+MONTH(EVENT_DATE)
HAVING COUNT(*) > 1 

答案 4 :(得分:0)

您需要两个级别的聚合。首先获得一个月内有多行的用户。然后按年,月分组,以获取特定月份的用户数。

@Override
protected void onCreate(Bundle savedInstanceState) {
    Preferences.applyTheme(this);
    getDelegate().installViewFactory();
    getDelegate().onCreate(savedInstanceState);
    super.onCreate(savedInstanceState);
    setToolbar();
    addPreferencesFromResource(R.xml.preferences);
    Preferences.sync(getPreferenceManager());
    mListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            Preferences.sync(getPreferenceManager(), key);
            if (key.equals(getString(R.string.pref_theme))) {
                finish();
                final Intent intent = IntentCompat.makeMainActivity(new ComponentName(
                        SettingsActivity.this, MainActivity.class));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
            }
        }
    };
}