sql distinct + count

时间:2015-10-19 20:26:31

标签: php sql

我想要做的是为每个用户计算同一列的特定实例。

例如:
vagt_type可能具有“timeloen”的值10倍,其中usr = 1和“prov”的值为该用户的2倍。我需要在单独的列中进行计数,并且我使用DISTINCT来仅获取每个usr一次。

以下是我到目前为止所做的工作,但它会计算vagt_type的所有实例,并且出于某种原因不受cast日期到期的影响:

$test = $wpdb->get_results("SELECT distinct m.usr, CONCAT(n1.meta_value, ' ', n2.meta_value) AS fl_name, count(m1.vagt_type) as timeloen
FROM $main_table as m
LEFT JOIN Lausten_usermeta n1 ON m.usr=n1.user_id and n1.meta_key = 'first_name'
LEFT JOIN Lausten_usermeta n2 ON m.usr=n2.user_id and n2.meta_key = 'last_name'
LEFT JOIN $main_table m1 ON m.usr=m1.usr and m1.vagt_type = 'timeloen'
WHERE m.vagtDato BETWEEN CAST('$start' AS DATE) AND CAST('$end' AS DATE)
", ARRAY_A);

修改 我的桌子的例子:

 id | usr | vagtDato   |  vagt_type
 13 |   1 | 2015-09-05 |    kursus
 16 |   1 | 2015-09-01 |    kursus
 11 |   1 | 2015-09-03 |    trappetur
 10 |   1 | 2015-09-02 |    provision
 9  |   1 | 2015-09-01 |    timeloen    
 15 |   1 | 2015-09-04 |    sygedag
 17 |   1 | 2015-09-02 |    timeloen    
 18 |   29| 2015-09-18 |    timeloen    
 19 |   1 | 2015-10-01 |    timeloen    

另一个表只有join到用户表,在这种情况下它并不重要,因为我只使用它来CONCAT用户的全名。

预期结果:

usr | timeloen | provision | sygedag
1   | 3        | 1         | 1
29  | 1        | 0         | 0

编辑: - 希望这有助于别人:) 最终成为我的整体解决方案:

$test = $wpdb->get_results("SELECT a.usr, a.vagtDato, b.timeloen, c.provision, d.kursus, e.trappetur, f.sygedag
FROM $main_table a
LEFT JOIN (SELECT usr, count(vagt_type) as timeloen
FROM $main_table  WHERE vagt_type = 'timeloen'
AND vagtDato between DATE('$start') AND DATE('$end')
GROUP BY usr ) b on b.usr=a.usr

LEFT JOIN (SELECT usr, count(vagt_type) as provision
FROM $main_table  WHERE vagt_type = 'provision'
AND vagtDato between DATE('$start') AND DATE('$end')
GROUP BY usr ) c on c.usr=a.usr

LEFT JOIN (SELECT usr, count(vagt_type) as kursus
FROM $main_table  WHERE vagt_type = 'kursus'
AND vagtDato between DATE('$start') AND DATE('$end')
GROUP BY usr ) d on d.usr=a.usr

LEFT JOIN (SELECT usr, count(vagt_type) as trappetur
FROM $main_table  WHERE vagt_type = 'trappetur'
AND vagtDato between DATE('$start') AND DATE('$end')
GROUP BY usr ) e on e.usr=a.usr

LEFT JOIN (SELECT usr, count(vagt_type) as sygedag
FROM $main_table  WHERE vagt_type = 'sygedag'
AND vagtDato between DATE('$start') AND DATE('$end')
GROUP BY usr ) f on f.usr=a.usr

WHERE a.vagtDato between DATE('$start') AND DATE('$end')
GROUP BY a.usr
", ARRAY_A);

1 个答案:

答案 0 :(得分:0)

我相信你必须提出类似的内容:

SELECT
    usr
    , ( SELECT( count( * ) FROM $TABLE where vagt_type = 'timeloen' ) AS timeloen
    , ( SELECT( count( * ) FROM $TABLE where vagt_type = 'provision ' ) AS provision 
    , ( SELECT( count( * ) FROM $TABLE where vagt_type = 'sygedag' ) AS sygedag
FROM ( $main_table )
    ( $LEFTJOINS )
GROUP BY usr --to get the distincts users

SELECT
    usr
    , count( * )
FROM ( $main_table )
    ( $LEFTJOINS )
GROUP BY 1, 2 --to get the distincts users