跨多个非唯一列的唯一记录

时间:2017-01-25 19:28:06

标签: mysql sql

我有一个用户表(tbl)在同一日期有多次扫描,有些用户在多个日期有多次扫描。

stdOutFILE = PerlIO_findFILE(PerlIO_stderr()); // convert Perl's stdout to stdio FILE handle

fdStdOutOriginal = fileno(stdOutFILE);         // get descriptor

if ( fdStdOutOriginal >= 0 ) {

    relocatedStdOut = dup(fdStdOutOriginal);   // relocate stdOut for external writing

    if ( relocatedStdOut >= 0 )
    {
        if ( pipe(fdPipeStdOut) == 0 )         // create pipe for forwarding to stderr
        {
            // this has to be done on win32:
            // if ( dup2(fdPipeStdOut[1], fdStdOutOriginal)  == 0 ) // hang pipe on stdOut

            dup2(fdPipeStdOut[1], fdStdOutOriginal);

            if( errno == 0 ) {
                // do some funny stuff
            } else {
                // report error
            }
        }
    }
}

我想要每个用户的唯一日期数(与每个日期发生的扫描次数无关),如下所示:

user    date        scan
andy    20160301    T1
andy    20160301    T2
andy    20160301    T1
andy    20160401    T1
andy    20160401    T2
lee     20160401    T1
lee     20160401    T2
lee     20160701    T1
lee     20160701    T2
lee     20160801    T1
lee     20160801    T2
tom     20160501    T1
tom     20160501    T2
tom     20160501    T2

我尝试了几件事,但我最接近的就是这个简单的查询:

user    NumVisits
andy    2
lee     3
tom     1

产生:

SELECT user, COUNT(*) NumVisits FROM tbl GROUP BY user HAVING NumVisits > 1;

此输出的问题在于它考虑了每个日期的多次扫描。任何人都可以帮我弄清楚如何获得这个输出吗?

user    NumVisits
andy    5
lee     6
tom     3

1 个答案:

答案 0 :(得分:1)

使用Count(distinct column)

SELECT
  user,
  COUNT(distinct date) NumVisits
FROM tbl GROUP BY user