Help with sql calculation

Suppose I have a table with two columns (status and date) as shown below:

status: U  T  U  U  L       
date:   12 14 15 16 17

Is it possible (using only 1 SQL statement) to count the number of different values ​​in a status? I.e:

  • Amount (U) = 3
  • counter (T) = 1
  • Amount (L) = 2
  • Amount (P) = 0

Can I do this with 1 SQL query?

Note. I have static values ​​in status. I can only have (utlp)

+3
source share
4 answers

This will return a row for each statusand a counter in the second column:

SELECT Status, COUNT(*) Cnt
FROM Tbl
GROUP BY Status

So he will return

Status  Cnt
 U       3
 T       1
 L       1

for your example (in a specific order). Use ORDER BYif you want to sort the results.

+1
source

Group By:

SELECT Status, Count(Status)
FROM table
GROUP BY Status

P = 0, P . , , , (.. 0).

SQL , .

+3

, , .

SELECT COUNT(*) as StatusCount, Status
FROM MyTable
GROUP BY Status
+1

P, , , .

SELECT COUNT(A.Status), B.Status
  FROM AnonymousTable AS A RIGHT OUTER JOIN
       (SELECT 'P' AS Status FROM Dual
        UNION
        SELECT 'U' AS Status FROM Dual
        UNION
        SELECT 'L' AS Status FROM Dual
        UNION
        SELECT 'T' AS Status FROM Dual
       ) AS B ON A.Status = B.Status
 GROUP BY B.Status;

4-way UNION - ; . , Dual ( Oracle).

COUNT (A.Status) counts the number of non-zero values ​​in A.Status. RIGHT OUTER JOIN displays a row from B with Status = 'P' and concatenates it with a single NULL for A.Status, which therefore COUNT (A.Status) is considered equal to zero. If you used COUNT (*), you would get 1 to count.

0
source

Source: https://habr.com/ru/post/1734210/


All Articles