H
H
HAtan2021-04-21 20:02:27
SQL
HAtan, 2021-04-21 20:02:27

How to find the balance for each user (sum per operator of each user)?

How can I calculate the amount by numbers with a specific operator? For example, I want to define with the operator code "90". But if you use the query below, then problems immediately pop up in that you need to add the country code or "___90%" so the search is done. Also, if you use OR, then if there is at least one match, it will count 3 values, if AND is used, then you need a complete match in 3 columns.
60805523927d1949283877.png

SELECT  ID, tel_balance1 + tel_balance2 + tel_balance3
 FROM    telephone WHERE tel1 LIKE "38090%" OR tel2 LIKE "38090%" OR tel3 LIKE "38090%"

COR
608059ce77a81582940655.png
CREATE TABLE `telephone`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `tel1` bigint(20) UNSIGNED NULL DEFAULT NULL,
  `tel2` bigint(20) UNSIGNED NULL DEFAULT NULL,
  `tel3` bigint(20) UNSIGNED NULL DEFAULT NULL,
  `tel_balance1` decimal(65, 2) NULL DEFAULT 0,
  `tel_balance2` decimal(65, 2) NULL DEFAULT 0,
  `tel_balance3` decimal(65, 2) NULL DEFAULT 0,
  `birthday` date NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
)


And another question, is it possible to somehow calculate the number of numbers with certain operators.
For example

operator code | count
50 | 10
63 | 15
67 | 1
90 | eight

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Slava Rozhnev, 2021-04-21
@rozhnev

You can do this:

SELECT 
  ID, 
  tel_balance1 * (tel1 LIKE "38090%") + 
  tel_balance2 * (tel2 LIKE "38090%") + 
  tel_balance3 * (tel3 LIKE "38090%") AS balance_38090
FROM 
  telephone 
WHERE 
  tel1 LIKE "38090%" 
  OR tel2 LIKE "38090%" 
  OR tel3 LIKE "38090%"
;

SQL online
Although it is better to read about data normalization and bring tables to normal form

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question