2016-02-27 2 views
-1

В следующем запросе есть три соединения таблицы, то есть ration_card_and_member_count_orignal_tp, commodityallotment и AllotmentSchedules. этот запрос возвращает данные в соответствии с fps, кодом района и типом карты. Я хочу, чтобы преобразовать результат запроса из строки в столбцеКак преобразовать строки int столбцов в sql

Select 
    a.qty, a.commodity, 
    c.rationcardcount, c.district_code, c.fps_id, 
    a.qty * c.rationcardcount totalquantity, 
    c.card_type, d.AllotmentType 
from 
    (select 
     sum(rccount) rationcardcount, district_code, 
     fps_id, card_type 
    from 
     [ration_card_and_member_count_orignal_tp] 
    where 
     card_type in (01, 02, 03) 
     and district_code = 033 
     and fps_id = 2668 
    group by 
     fps_id, card_type, district_code) c, 
    CommodityAllotments a 
inner join 
    AllotmentSchedules d on a.Allotment_Schedule_id = d.Schedule_id 
where 
    d.AllotmentType = 1 
    and a.card_type_id in (01, 02, 03) 
    and (2016 between cast(Allotment_From_Year as int) and cast(Allotment_To_Year as int)) 
    and (2016 between cast(Allotment_From_Year as int) and cast(Allotment_To_Year as int)) 
    and (2 between cast(Allotment_From_Month as int) and Allotment_To_Month as int)) 
    and (2 between cast(Allotment_From_Month as int) and cast(Allotment_To_Month as int)) 

Выше запрос возвращает данные в следующем формате:

qty  commodity rationcardcount district_code fps_id totalquantity  card_type AllotmentType 
15  Rice  258    033    2668  3870     01  1 
15  Rice  2    033    2668  30     02  1 
15  Rice  53    033    2668  795     03  1 
20  Wheat  258    033    2668  5160     01  1 
20  Wheat  2    033    2668  40     02  1 
20  Wheat  53    033    2668  1060     03  1 

Я хочу, чтобы отобразить данные в следующем формате:

qty commodity district_code fps_id 01  02 03 

    15 Rice   033    2668 3870 30 795 

    20 Wheat  033    2668 5160 40 1060 

ответ

1

Pivot функция должна сделать трюк,

SELECT [qty],[commodity],[district_code],[fpd_id],[01],[02],[03] 
FROM [dbo].<YOUR_TABLENAME> 
PIVOT 
(
     SUM(totalquantity) 
     FOR [card_type] IN ([01],[02],[03]) 
) AS P 
Смежные вопросы