webForumDet fria alternativet

Nu ska det räknas!

Databaser & SQL

2 svar · 246 visningar · startad av Troxy

Medlem sedan mars 20041 505 inlägg
Frågan#1

Säg att jag har en tabell som ser ut såhär:

id        status
----------------
1         1
2         2
3         1
4         2
5         1
6         3
7         2
8         2
9         1
10        1
11        3

Jag undrar nu hur man räknar antalet poster per status, och får ut resultatet såhär:

status1   status2   status3   totalt
------------------------------------
5         4         2         11

Tack på förhand!

Medlem sedan feb. 20011 198 inlägg
#2

Om status inte är dynamiskt går det med ren SQL.
Detta funkar med MSSQL.

select (select count(status) from tbl where status=1) status1, (select count(status) from tbl where status=2) status2, (select count(status) from tbl where status=3) status3, (select count(status) from tbl where status=4) status4,(select count(status) from tbl where status=5) status5, (select count(status) from tbl) totalt
Medlem sedan mars 20041 505 inlägg
#3

Tack så mycket!

257 ms totalt · 4 externa anrop · v20260731065814-full.e96017d9
121 ms — deklarationer (db)
0 ms — hämta statistik (cache)
131 ms — hämta tråd, inlägg och bilagor (db)
123 ms — ändringar (db)