I am trying to make the table below look like so
Current Query:
SELECT m.typeID, t.typeName, m.quantity, t.description
FROM invTypeMaterials AS m
LEFT JOIN invTypes AS t
ON m.materialTypeID = t.typeID
LEFT JOIN invTypes
ON m.TypeID = t.typeID
WHERE m.typeID = 10039
Current Result
typeID typeName quantity description
10039 Tritanium 71 The main building block in space structures. A ver...
10039 Pyerite 24 A soft crystal-like mineral with a very distinguis...
10039 Mexallon 1 Very flexible metallic mineral, dull to bright sil...
What I'm look for is for it to show up like this
typeID Tritanium Pyerite mexallon description
10039 71 24 1 Doesn't matter
I have tried combinations of left join, outer join, inner join etc and cant make it work. I also tried group_concat which I think is what I need but cant get the columns right
Thanks
EDIT: I have the column looking like I want by using the following:
SELECT m1.typeID,
SUM(CASE WHEN m1.materialTypeID = 34 THEN m1.quantity ELSE 0 END) AS Tritanium,
SUM(CASE WHEN m1.materialTypeID = 35 THEN m1.quantity ELSE 0 END) AS Pyerite,
SUM(CASE WHEN m1.materialTypeID = 36 THEN m1.quantity ELSE 0 END) AS Mexallon,
SUM(CASE WHEN m1.materialTypeID = 37 THEN m1.quantity ELSE 0 END) AS Isogen,
SUM(CASE WHEN m1.materialTypeID = 38 THEN m1.quantity ELSE 0 END) AS Nocxium,
SUM(CASE WHEN m1.materialTypeID = 39 THEN m1.quantity ELSE 0 END) AS Zydrine,
SUM(CASE WHEN m1.materialTypeID = 40 THEN m1.quantity ELSE 0 END) AS Megacyte,
SUM(CASE WHEN m1.materialTypeID = 11399 THEN m1.quantity ELSE 0 END) AS Morphite
FROM invTypeMaterials AS m1
WHERE m1.typeID = 10039
RESULT:
typeID Tritanium Pyerite Mexallon Isogen Nocxium Zydrine Megacyte Morphite
10039 71 24 1 0 0 0 0 0
When i take out the "WHERE" clause and try to pull them all it shows up like this:
typeID Tritanium Pyerite Mexallon Isogen Nocxium Zydrine Megacyte Morphite
18 13989190531 1301687143 261706229 54807927 14277967 4262960 1540121 40701
Any ideas?
UPDATE 2: I got it, the GROUP BY did the trick
Assuming the typeName values are always the same you can use subqueries in the select section of your query to get the values you want.
$sql = "SELECT m.typeID,
(SELECT m.quantity FROM invTypes AS t WHERE m.materialTypeID = t.typeID AND t.typeName = 'Tritanium') as Tritanium,
(SELECT m.quantity FROM invTypes AS t WHERE m.materialTypeID = t.typeID AND t.typeName = 'Pyerite') as Pyerite,
(SELECT m.quantity FROM invTypes AS t WHERE m.materialTypeID = t.typeID AND t.typeName = 'Mexallon') as Mexallon
FROM invTypeMaterials AS m
WHERE m.typeID = 10039";
I don't think there's any way in SQL to generate dynamic columns. If you can write dynamic SQL, then yes but in pure SQL, I don't think so.
If you're willing to hard-code the columns then you can do
SELECT
m.TypeID,
MAX(CASE
WHEN t.typeName = 'Tritanium' THEN m.quantity
ELSE 0
END) Tritanium,
MAX(CASE
WHEN t.typeName = 'Pyerite' THEN m.quantity
ELSE 0
END) Pyerite,
MAX(CASE
WHEN t.typeName = 'Mexallon' THEN m.quantity
ELSE 0
END) Mexallon
FROM
[your FROM clause]
WHERE
[your WHERE clause]
GROUP BY
m.TypeID;
We have pivot clause in oracle to do similar kind of functionality.
It helps in writing cross tabulation query i.e., we can aggregate results and rotate rows into columns.
tried the below with some sample data:
create table types(typeid number,typename varchar2(20),
quantity number);
insert into types values(1,'xx',11);
insert into types values(1,'yy',121);
insert into types values(1,'zz',113);
delete from types where typeid in(2,3);
select *from
(select typeid,typename,quantity from types)
pivot
(
sum(quantity)
for typename in('xx','yy','zz')
)
typeid xx yy zz
1 11 121 113
Related
Why DISTINCT UID doesn't work in my code below?
$q = mysql_fetch_array(mysql_query("SELECT COUNT(DISTINCT UID) AS TOTAL,
SUM(CASE WHEN SYSTEM = 'Android' THEN 1 ELSE 0 END) AS A,
SUM(CASE WHEN SYSTEM = 'IOS' THEN 1 ELSE 0 END) AS I,
SUM(CASE WHEN SYSTEM = 'Windows' THEN 1 ELSE 0 END) AS W FROM user_visits"));
The query returns all items from the database selected even I put DISTINCT UID or *. Same result.
The distinct keyword is supposed to be outside like below,
SELECT DISTINCT column1, column2, ...
FROM table_name;
?
Also, you are trying to sum few things, It should be something like below,
SELECT UID, COUNT(UID) AS TOTAL,
SUM(CASE WHEN SYSTEM = 'Android' THEN 1 ELSE 0 END) AS A,
SUM(CASE WHEN SYSTEM = 'IOS' THEN 1 ELSE 0 END) AS I,
SUM(CASE WHEN SYSTEM = 'Windows' THEN 1 ELSE 0 END) AS W FROM user_visits
GROUP BY UID
with aggregate (group by)
In my table1 there is date like:
id value
1 500
2 400
3 300
4 200
5 100
I want to set the data above within the show table:
d1 d2 d3 d4 d5
500 400 300 200 100
I am using the following sql query.
"SELECT `value` as d1 from `table1` WHERE `id`=1"
"SELECT `value` as d2 from `table1` WHERE `id`=2"
"SELECT `value` as d3 from `table1` WHERE `id`=3"
"SELECT `value` as d4 from `table1` WHERE `id`=4"
"SELECT `value` as d5 from `table1` WHERE `id`=5"
How will I make all the queries within single sql query?
I would use aggregation:
select max(case when id = 1 then value end) as d1,
max(case when id = 2 then value end) as d2,
max(case when id = 3 then value end) as d3,
max(case when id = 4 then value end) as d4,
max(case when id = 5 then value end) as d5
from t;
If you can work with separate rows, just filter the values:
select id,
value
from t
where id in (1,2,3,4,5);
If you need all the values in a single row, use where to filter all the rows and conditional aggregation to pivot the data:
select max(case when id = 1 then value end) as d1,
max(case when id = 2 then value end) as d2,
max(case when id = 3 then value end) as d3,
max(case when id = 4 then value end) as d4,
max(case when id = 5 then value end) as d5
from t
where id in (1,2,3,4,5);
I have a table in my database named contacts and a table named views.
On the table contacts I have the following fields:
id
status
first_name
last_name
The status can be cold, prospect or lost.
On the table views I have the following fields:
user_id
art_views
art_title
The relation between those 2 tables is id and user_id.
I need a query to make a new html table with the following columns:
art_title
cold
prospect
lost
Now I have the following query (UPDATED):
SELECT
v.art_title,
SUM(CASE c.status WHEN 'cold' THEN v.art_views ELSE 0 END) cold,
SUM(CASE c.status WHEN 'prospect' THEN v.art_views ELSE 0 END) prospect,
SUM(CASE c.status WHEN 'lost' THEN v.art_views ELSE 0 END) lost
FROM views v
JOIN contacts c ON v.user_id = c.id
GROUP BY v.art_title
This query is working now (thanks to Gerv) but i still have users who don't have a status. So i leave the field user_id in the table 'views' empty. How can i change the query for those users so i can count them also?
I tried to: SUM(CASE v.user_id WHEN ' ' THEN v.art_views ELSE 0 END) test,
but with no result here.
You can switch the logic by selecting from the views table and joining de contacts table.
Below query will pivot the status with a CASE clause
SELECT
v.art_title,
SUM(CASE c.status WHEN 'cold' THEN v.art_views ELSE 0 END) cold,
SUM(CASE c.status WHEN 'prospect' THEN v.art_views ELSE 0 END) prospect,
SUM(CASE c.status WHEN 'lost' THEN v.art_views ELSE 0 END) lost,
SUM(CASE c.status WHEN NULL THEN v.art_views ELSE 0 END) no_user
FROM views v
LEFT JOIN contacts c ON v.user_id = c.id
GROUP BY v.art_title
ORDER BY (cold+lost+prospect+no_user) DESC
LIMIT 10
Try
SELECT art_title, SUM(art_views), status FROM contacts AS c INNER JOIN views AS v ON v.user_id = c.id GROUP BY v.art_title, c.status
I have this tbl_religion with fieldname creldesc
and tbl_member with these fields
and I have this query to count all existing religion in tbl_member and count also the no. of male and female with that religion so i made this query :
SELECT m.creldesc as type,
COUNT(m.creldesc) as total,
SUM(CASE WHEN m.cgender='Male' THEN 1 ELSE 0 END) as male,
SUM(CASE WHEN m.cgender='Female' THEN 1 ELSE 0 END) as female
FROM tbl_member as m, tbl_barangay as b, tbl_household as h
WHERE m.chholdnumber = h.chholdnumber and h.cbrgycode=b.cbrgycode and b.cbrgyname = 'AGAO'
and m.crelationdesc !='Brgy. Captain'
GROUP BY m.creldesc
ORDER BY tot DESC;
and get this output :
what I want to achieve is also display the remaining religion from tbl_religion with 0 as value. I made a left join but get an error. Can someone help me how can I achive that ?
type total male female
Roman Catholic 7 4 3
Baptist 3 1 2
Islam 3 3 0
Iglesia ni Cristo 1 1 0
Free Methodist 1 1 0
Ang Dating Daan 1 0 1
Aglipay/Filipinsta 0 0 0
All the Gospel 0 0 0
Alpha Omega 0 0 0
and so on.............................
Use same joining approach for all tables, like this:
SELECT m.creldesc as type, COUNT(m.creldesc) as tot,
SUM(CASE WHEN m.cgender='Male' THEN 1 ELSE 0 END) as male,
SUM(CASE WHEN m.cgender='Female' THEN 1 ELSE 0 END) as female
FROM tbl_religion
LEFT JOIN tbl_member as m
ON tbl_religion.creldesc=m.creldesc
LEFT JOIN tbl_household as h
ON m.chholdnumber = h.chholdnumber
LEFT JOIN tbl_barangay as b
ON h.cbrgycode=b.cbrgycode
WHERE b.cbrgyname = 'AGAO' AND m.crelationdesc !='Brgy. Captain'
GROUP BY m.creldesc
ORDER BY tot DESC
Your current query approach of ... FROM tbl_member, tbl_barangay, tbl_household LEFT JOIN tbl_religion ... is wrong and will produce syntax error.
You can not make this:
FROM #TABLE1, #TABLE2, #TABLE3 LEFT JOIN #TABLE0 ON ...
You can select items only from a table at once... same for join.
SELECT m.creldesc as type,
COUNT(m.creldesc) as tot,
SUM(CASE WHEN m.cgender='Male' THEN 1 ELSE 0 END) as male,
SUM(CASE WHEN m.cgender='Female' THEN 1 ELSE 0 END) as female
FROM tbl_member as m
LEFT JOIN tbl_religion z ON z.creldesc = m.creldesc
LEFT JOIN tbl_barangay h ON h.cbrgycode=b.cbrgycode
SO ON.... WITH JOINS
GROUP BY m.creldesc
UPDATE WOKING CODE:
SELECT m.creldesc as type, COUNT(m.creldesc) as tot, SUM(CASE WHEN m.cgender='Male' THEN 1 ELSE 0 END) as male,
SUM(CASE WHEN m.cgender='Female' THEN 1 ELSE 0 END) as female
FROM tbl_member as m
LEFT JOIN tbl_religion r ON r.creldesc = m.creldesc
LEFT JOIN tbl_barangay as b ON m.chholdnumber = b.cbrgycode
LEFT JOIN tbl_household as h ON h.cbrgycode = b.cbrgycode
WHERE b.cbrgyname = 'AGAO' and m.crelationdesc !='Brgy. Captain'
GROUP BY m.creldesc
ORDER BY tot DESC
Here's what I did:
SELECT tbl_member.creldesc AS type,
COUNT(tbl_member.creldesc) AS total,
SUM(CASE WHEN tbl_member.cgender::text = 'Male'::text THEN 1 ELSE 0 END) AS male,
SUM(CASE WHEN tbl_member.cgender::text = 'Female'::text THEN 1 ELSE 0 END) AS female
FROM tbl_member
GROUP BY tbl_member.creldesc
UNION
SELECT b.creldesc AS type, 0 AS total, 0 AS male, 0 AS female
FROM tbl_religion b
WHERE NOT (b.creldesc::text IN
( SELECT DISTINCT tbl_member.creldesc FROM tbl_member))
GROUP BY b.creldesc;
and here is it's output :
that's all :) I used UNION instead of LEFT JOIN.
suppose this
user table:
[id] [mail] [pass]
happen table:
[id] [uid] [date] [content]
vote table
[uid] [hid] [type] [datetime]
1 user can have 0 or more happen, 1 happen can have 0 or more votes..
I want to get the total number of votes for a specific happen
SELECT
H.*,
SUM(CASE WHEN V.type='C' THEN 1 ELSE 0 END) AS upvotes,
SUM(CASE WHEN V.type='R' THEN 1 ELSE 0 END) AS downvotes
FROM
happens H
LEFT JOIN
votes AS V
ON V.hid = H.id
WHERE
H.uid = :uid
the problem is that if no votes is associated on a happen I get a null row from mysql, not EMPTY but NULL
how can I avoid this null result?
[edit]
some try:
basic
SELECT H.* FROM happens H LEFT JOIN votes AS V ON V.hid = H.id WHERE H.uid = '178d937'
result -> empty
All other try with the SUM, COUNT, HAVING ect ect gives:
[id] [uid] [what] [latitude] [longitude] [date] [time] [hide] [upvotes] [downvotes]
NULL NULL NULL NULL NULL NULL NULL NULL 0 0
Use HAVING to check for the null
SELECT
H.*,
SUM(CASE WHEN V.type='C' THEN 1 ELSE 0 END) AS upvotes,
SUM(CASE WHEN V.type='R' THEN 1 ELSE 0 END) AS downvotes
FROM
happens H
LEFT JOIN
votes AS V
ON V.hid = H.id
WHERE
H.uid = :uid
HAVING upvotes IS NOT NULL
SELECT H.*,
SUM(IFNULL(V.type = 'C', 0)) AS upvotes,
SUM(IFNULL(V.type = 'R', 0)) AS downvotes
If you change your LEFT JOIN to an INNER JOIN (or just JOIN) you will only get the happens records that have at least 1 associated record in the votes table:
SELECT
H.*,
SUM(CASE WHEN V.type='C' THEN 1 ELSE 0 END) AS upvotes,
SUM(CASE WHEN V.type='R' THEN 1 ELSE 0 END) AS downvotes
FROM
happens H
INNER JOIN
votes AS V
ON V.hid = H.id
WHERE
H.uid = :uid
Check out http://www.w3schools.com/sql/sql_join.asp for info on the different join types.
EDIT:
Ok, so to get all happens, but with 0 for those without votes try (add COALESCE):
SELECT
H.*,
COALESCE(SUM(CASE WHEN V.type='C' THEN 1 ELSE 0 END),0) AS upvotes,
COALESCE(SUM(CASE WHEN V.type='R' THEN 1 ELSE 0 END),0) AS downvotes
FROM
happens H
LEFT JOIN
votes AS V
ON V.hid = H.id
WHERE
H.uid = :uid
SELECT
H.*,
COALESCE(SUM(CASE WHEN V.type='C' THEN 1 ELSE 0 END), 0) AS upvotes,
COALESCE(SUM(CASE WHEN V.type='R' THEN 1 ELSE 0 END), 0) AS downvotes
Left Join will return all rows on the left and NULL values on the right if ON condition does not match.Use Inner Join.
solved using 2 statement
first select all happen
second select all votes for every happen and merging the values
here is the solution from my php happenModel class:
public function getUserHappensWithVotes() {
$selectQuery = <<<QUERY
SELECT
SUM(CASE WHEN V.type='C' THEN 1 ELSE 0 END) AS upvotes,
SUM(CASE WHEN V.type='R' THEN 1 ELSE 0 END) AS downvotes
FROM
votes V
WHERE
V.uid = :uid
AND
V.hid = :hid
QUERY;
// get all happen as array of class
$userHappens = $this->userHappens;
// empty container
$happenWithVotes = array();
foreach( $userHappens AS $happen ) {
$sql = $this->pdo->prepare( $selectQuery );
$sql->execute( array( ':uid'=>$happen->uid, ':hid'=>$happen->id ) );
// fetching the count of up and down votes of every happen
$votes = $sql->fetch( PDO::FETCH_ASSOC );
// merging happen class as array with votes
$happen = array_merge( (array) $happen, $votes );
// rebuild the userHappen array
$happenWithVotes[] = (object) $happen;
}
if ( $this->encoder ) {
return $this->encoder->setData( $this->parse( $happenWithVotes ) )->encode();
} else {
return $this->parse( $happenWithVotes );
}
}