将查询列检索为行

时间:2011-08-23 14:37:27

标签: mysql

我有一个包含以下列的表:

BillNo   -- Integer
BillDate -- DateTime
Qty      -- decimal
ItemName -- varchar

我想以这种格式检索结果:

**ITEMNAME...JAN-2011.....FEB-2011....MAR-2011** 
ITEM1 ......... 20 ..............19................18
ITEM2 ......... 23 ..............10................9

我尝试了这个显示正确结果的查询,但我想将第三列转换为具有不同值的行:

SELECT ITEMNAME, SUM(QTY), DATE_FORMAT(BILLDATE,'%M-%Y') FROM BILLITEMS
GROUP BY BILLDATE
ORDER BY YEAR(BILLDATE) DESC, MONTH(BILLDATE), ITEMNAME;

1 个答案:

答案 0 :(得分:0)

尝试使用下面的查询,但它适用于特定年份

SELECT ITEMNAME, year_bill, SUM(jan), SUM(feb), .... from (
    select case when MONTH(BILLDATE) = 1 then QTY else 0 end as jan,
    case when MONTH(BILLDATE) = 2 then QTY else 0 end as feb,
    case when MONTH(BILLDATE) = 3 then QTY else 0 end as mar,
    ITEMNAME,
    YEAR(BILLDATE) as year_bill
from BILLITEMS) as temp
GROUP BY ITEMNAME, year_bill