List:General Discussion« Previous MessageNext Message »
From:mathias fatene Date:April 26 2005 3:48am
Subject:RE: Crosstab in Mysql
View as plain text  
Hi,
What do you obtain with :
Select FK_partic,
Sum(IF(insumo_or = "Animal1", cantidad_or, 0) ) AS "Animal1", 
Sum(IF (insumo_or = "Animal2", cantidad_or, 0) ) AS "Animal2", 
Sum(IF (insumo_or = "Animal3", cantidad_or, 0) ) AS "Animal3", 
Sum(IF (insumo_or = "Animal4", cantidad_or, 0) ) AS "Animal4", 
Sum(IF (insumo_or = "Animal5", cantidad_or, 0) ) AS "Animal5", 
Sum(IF (insumo_or = "Animal6", cantidad_or, 0) ) AS "Animal6"
FROM tbl_ISv2CROriginal
Group by FK_partic

?


Best Regards
--------------------
Mathias FATENE
 
Hope that helps
*This not an official mysql support answer
 


-----Original Message-----
From: Alvaro Cobo [mailto:coboalvaro@stripped] 
Sent: mardi 26 avril 2005 04:38
To: mysql@stripped
Subject: Crosstab in Mysql


Hi guys: 

I am quite new in SQL and I need to build a crosstab based in two tables
using Mysql and PHP, but it is becoming quite dificult. 

I've got the next query, but it keeps giving the next error: 

"#1241 - Operand should contain 1 column(s)" 

/*GENERAL EXPLANATION OF THE QUERY

I work in a project to give animals to farmers: I have two tables: 

tbl_ISv2CRfamilia with the families which are going to receive animals. 
    (PK_partic, int(11), Autonumbering ID (PK); 
    FK_IS; varchar(255); Foreign key which conects to the project table
    nombre_partic, varchar(255), Name of the family
    OB_familia, varchar(255), community of the family)

tbl_ISv2CROriginal with the animales they actually have received. 
    (FK_partic, int(11), Foreign key which conects to the family ID
    insumo_or, varchar(255), Animal given
    cantidad_or, int(11), number of animals given of this specie)

And I need to have a table like this: 

Family,     animal1,     animal2,     animal3,     ...,     animaln
John Smith     3    4    0    1    3    ...     0
*/


The query and subquiery is as follows. 

SELECT tbl_ISv2CRfamilia.PK_partic, 
tbl_ISv2CRfamilia.FK_IS, 
tbl_ISv2CRfamilia.OB_familia, 
(SELECT Sum(
IF (
insumo_or = "Animal1", cantidad_or, 0
) ) AS "Animal1", Sum(
IF (
insumo_or = "Animal2", cantidad_or, 0
) ) AS "Animal2", Sum(
IF (
insumo_or = "Animal3", cantidad_or, 0
) ) AS "Animal3", Sum(
IF (
insumo_or = "Animal4", cantidad_or, 0
) ) AS "Animal4", Sum(
IF (
insumo_or = "Animal5", cantidad_or, 0
) ) AS "Animal5", Sum(
IF (
insumo_or = "Animal6", cantidad_or, 0
) ) AS "Animal6"
FROM tbl_ISv2CROriginal
GROUP BY FK_partic
)
FROM tbl_ISv2CRfamilia
INNER JOIN tbl_ISv2CROriginal ON tbl_ISv2CRfamilia.PK_partic =
tbl_ISv2CROriginal.FK_partic GROUP BY FK_partic

What is wrong with that? I have tried everything, and no solution. 

Thanks in advance. 

Alvaro

Thread
Crosstab in MysqlAlvaro Cobo26 Apr
  • RE: Crosstab in Mysqlmathias fatene26 Apr
  • Re: Crosstab in MysqlPeter Brawley26 Apr
  • Re: Crosstab in MysqlAlvaro Cobo26 Apr