使用Mysql创建数据透视表时遇到问题。
实际查询如下
SELECT DISTINCT `bills_organization`.`name`,
IF(`bills_bill`.`os_status`=1,COUNT(`bills_bill`.`os_status`),NULL) AS Unnknown,
IF(`bills_bill`.`os_status`=2,COUNT(`bills_bill`.`os_status`),NULL) AS Introduced,
IF(`bills_bill`.`os_status`=3,COUNT(`bills_bill`.`os_status`),NULL) AS Passedonechamber,
IF(`bills_bill`.`os_status`=4,COUNT(`bills_bill`.`os_status`),NULL) AS Passedbothchambers,
IF(`bills_bill`.`os_status`=5,COUNT(`bills_bill`.`os_status`),NULL) AS Enacted
FROM `bills_mybill`
INNER JOIN `auth_user` ON (`bills_mybill`.`user_id` = `auth_user`.`id`)
LEFT OUTER JOIN `bills_bill` ON (`bills_mybill`.`bill_id` = `bills_bill`.`id`)
LEFT OUTER JOIN `bills_userprofile` ON (`auth_user`.`id` = `bills_userprofile`.`user_id`)
LEFT OUTER JOIN `bills_organization` ON (`bills_userprofile`.`organization_id` = `bills_organization`.`id`)
WHERE `bills_mybill`.`favorite` = TRUE
GROUP BY `bills_organization`.`name`,`bills_bill`.`os_status`
此输出如下
name Unnknown Introduced Passedonechamber Passedbothchambers Enacted NUL NULL 5 NULL NULL NULL NULL NULL NULL NULL 1 NULL AEE NULL 16 NULL NULL NULL AEE NULL NULL 1 NULL NULL AEE NULL NULL NULL 4 NULL AEE NULL NULL NULL NULL 2 Testing NULL 6 NULL NULL NULL Testing NULL NULL NULL 2 NULL Testing NULL NULL NULL NULL 6
我想要组织,并且在一行中计数。我不想要多行。
提前致谢。
答案 0 :(得分:0)
SELECT `bills_organization`.`name`,
SUM(`bills_bill`.`os_status`=1) AS Unnknown,
SUM(`bills_bill`.`os_status`=2) AS Introduced,
SUM(`bills_bill`.`os_status`=3) AS Passedonechamber,
SUM(`bills_bill`.`os_status`=4) AS Passedbothchambers,
SUM(`bills_bill`.`os_status`=5) AS Enacted
FROM `bills_mybill`
INNER JOIN `auth_user` ON (`bills_mybill`.`user_id` = `auth_user`.`id`)
LEFT OUTER JOIN `bills_bill` ON (`bills_mybill`.`bill_id` = `bills_bill`.`id`)
LEFT OUTER JOIN `bills_userprofile` ON (`auth_user`.`id` = `bills_userprofile`.`user_id`)
LEFT OUTER JOIN `bills_organization` ON (`bills_userprofile`.`organization_id` = `bills_organization`.`id`)
WHERE `bills_mybill`.`favorite` = TRUE
GROUP BY `bills_organization`.`name`