我想要做的是爲每個用戶統計同一列的特定實例。sql distinct + count
例如:
vagt_type
可能具有的「timeloen」 10倍的值,其中usr = 1
和「省」 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);
我們不禁要看看你的表格是如何相互關聯的,以及一些樣品數據和預期結果 –
是否讓人難以接受? –
'CAST('$''AS DATE)'是完全錯誤的。這是你應該首先解決的問題。如果您將每個參數與正確的數據類型綁定,PDO或mysqli將爲您執行此操作。 – Sebas