选择并计算性别= X的uniqe值

时间:2015-09-22 13:24:39

标签: sql join count oledb distinct

我有一个SQL查询:

SELECT t1.Nev, 
       Count(t2.Datum) AS Edzes_szam 
FROM   Adatok t1 
       INNER JOIN (SELECT DISTINCT Kod, 
                                   Datum 
                   FROM   Jelenlet 
                   WHERE  Datum LIKE '" + dtm_year_hkszpp_ym + "%') t2 
               ON t1.Azon_sima = t2.Kod 
GROUP  BY t1.Nev 

我想请求您帮助更改它,因为只有gender='X'必须计算在内。

此查询计算名称在所选月份中记录的次数。 我想为性别做一个过滤器。我必须采取这个where gender = 'X'的方式和地点。

我正在使用MSOLEDB。

2 个答案:

答案 0 :(得分:1)

您不需要子查询来处理您的工作:

SELECT A.Nev, Count(DISTINCT J.Datum) AS Edzes_szam 
FROM Adatok a INNER JOIN
     Jelenlet j
     ON A.Azon_sima = j.Kod AND
        j.Datum LIKE '" + dtm_year_hkszpp_ym + "%'
GROUP BY a.Nev ;

使用此结构,您只需在WHERE gender = <whatever>之前添加GROUP BY

您的代码类型表明您使用LIKE表示日期。不建议在任何数据库中使用。所有内置的日期和时间函数都优于LIKE

答案 1 :(得分:0)

太简单了。如果您在Adatok表中有性别列,请尝试: -

SELECT t1.Nev, 
   Count(t2.Datum) AS Edzes_szam 
FROM   Adatok t1 
   INNER JOIN (SELECT DISTINCT Kod, 
                               Datum 
               FROM   Jelenlet 
               WHERE  Datum LIKE '" + dtm_year_hkszpp_ym + "%') t2 
           ON t1.Azon_sima = t2.Kod 
WHERE t1.gender = 'X'
GROUP  BY t1.Nev

否则,试试这个: -

SELECT t1.Nev, 
   Count(t2.Datum) AS Edzes_szam 
FROM   Adatok t1 
   INNER JOIN (SELECT DISTINCT Kod, 
                               Datum 
               FROM   Jelenlet 
               WHERE  Datum LIKE '" + dtm_year_hkszpp_ym + "%'
               AND gender = 'X') t2 
           ON t1.Azon_sima = t2.Kod 

GROUP  BY t1.Nev