This is my database table. How would i be able to select the bottom table from the database table?
Is it possible to create NameID and TypeID from unique names and types?
EDIT—
Ive got the type to work using case, since there are only 3 types.
SELECT
name, type, spending,
CASE type
WHEN 'Credit Card' THEN 1
WHEN 'Cash' THEN 2
WHEN 'Cheque' THEN 3
END AS typeID_
FROM spendtable
Would it be possible to do the same on the name column?
Thanks!
—-database table—-
Name Type
Spending
John Credit Card 550
Brian Cash
200
Frank Cheque
600
John Cash
150
John
Cash 300
Frank Credit
Card 200
—-table needed —-
NameID Name TypeID Type
Spending
1
John 1 Credit Card
550
2
Brian 2
Cash 200
3 Frank 3 Cheque
600
1 John 2 Cash
150
1 John 2 Cash
300
3 Frank 1 Credit Card 200
——-EDIT
I ended up using 2 queries and php to get the required table
function getInfo(){
SELECT
name, type, spending,
CASE type
WHEN 'Credit Card' THEN 1
WHEN 'Cash' THEN 2
WHEN 'Cheque' THEN 3
END AS typeID_
FROM spendtable
}
function getName(){
SELECT name
FROM spendtable
GROUP BY share_ ASC
}
$info_array = $this->getInfo();
$name_array = $this->getName();
for($i=0; $i<count($info_array); $i++){
$info_array[$i]['nameID'] = '';
for($j=0; $j<count($name_array); $j++){
if($info_array[$i]['nameID'] == $name_array[$j]){
$info_array[$i]['nameID'] = $j;
}
}
}
I was able to expand your existing query to support the
NameIDcolumn:As a design limitation, people stored in your database are only allowed to be named John, Brian, or Frank 🙂
Getting serious, assuming there are an unknown possible number of names I’m not sure you can (or would want to) do that kind of processing in the query. Instead, consider maintaining a separate
Nametable for keeping track of unique names:Your query could then join on this table:
Of course this would mean you needed to keep the
Nametable up to date, making sure to insert rows for new names.