如何在mysql中动态地将行转换为列

时间:2018-02-24 15:09:02

标签: mysql inner-join

我们正在尝试将行转换为列,以便以行方式显示。

给出一个survey_details表,看起来像

a busy cat

给出一个vehicle_category表,看起来像

a busy cat

我如何将行转换为列以获得计数

我想要的输出是

a busy cat

我们已尝试在此表上加入,但无法将行转换为列标题

select s.date,s.vehicle_id,v.category_name,count(s.vehicle_id) as vehicle_count from survey_details s inner join vehicle_category v on s.vehicle_id=v.vehicle_id group by s.vehicle_id;

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT C.Period,
  SUM(C.Bike) Bike,
  SUM(C.Car) Car,
  SUM(C.Truck) Truck,
  SUM(C.Total) Total
FROM 
  (SELECT 
    DATE_FORMAT(A.`date`,'%d/%m/%Y') Period, 
    SUM(if(B.category_name='Bike',1,0)) Bike,
    SUM(if(B.category_name='Car',1,0)) Car,
    SUM(if(B.category_name='Truck',1,0)) Truck,
    COUNT(*) Total
   FROM survey_details A JOIN vehicle_category B
   ON A.vehicle_id=B.vehicle_id
   GROUP BY DATE_FORMAT(A.`date`,'%d/%m/%Y'), B.category_name) C
GROUP BY C.PERIOD;

请参阅DEMO