问题
I am having trouble in getting the count(*) based on the condition.
Following is my data
id | user_id | key | value
---+---------+------------+-------------------------
1 | 3434 | first_name | Brandon
2 | 3434 | last_name | Johnson,Brett,Jack
3 | 3434 | street_add | 123 main
4 | 3434 | city | ocean beach
5 | 3434 | state | Texas
My query is
SELECT
COUNT(*)
from
CUSTOMER c
where
c.key = 'last_name'
and
c.value;
I can't pass c.value
to the query like c.value = Johnson,Brett,Jack
as it can change randomly each time. So it has to be generic.
I am expecting the value should be 3 it has 3 value Johnson,Brett,Jack. But I keep getting different errors each time.
2nd question
I also want to assign it to a variable Like below
DECLARE
idNumber PLS_INTEGER;
BEGIN
Select
COUNT(*)
into
idNumber
from
CUSTOMER c
where
c.key = 'last_name'
and
c.value;
DBMS_OUTPUT.PUT_LINE('ID NUMBER ' || idNumber);
END;
回答1:
I believe you need something like
select count(*)
from customer c
where c.key = 'lastName'
and c.value in ('Johnson', 'Brett', 'Jack')
so you can count all the customers
with last names including Johnson
, Brett
and Jack
.
With you current data model, if you want to find all people with a specific firstName
and lastName
you must join two instances of customer
table as
select count(*)
from customer c1
join customer c2 on c1.user_id = c2.user_id
where c1.key = 'firstName'
and c2.key = 'lastName'
and c1.value = 'John'
and c2.value = 'Doe'
and it goes more complex if you need to search upon more fields.
By the way, why do you use such a data-model in an RDBMS? If you have an schema-less model, why don't you use a NoSQL database such as Mongo?
来源:https://stackoverflow.com/questions/59461713/how-to-get-the-count-based-on-two-conditions