具有多列一列的数据透视表

时间:2017-07-14 04:48:08

标签: sql oracle

每个列都找到一个值,但它是否支持多值?

我的查询示例:

WITH
INPUT_LIST AS 
(SELECT 1 PRODUCT_ID, 1 TYPE_ID, 1000 PRICE FROM DUAL
UNION ALL
SELECT 2 PRODUCT_ID, 1 TYPE_ID, 1500 PRICE FROM DUAL
UNION ALL
SELECT 3 PRODUCT_ID, 2 TYPE_ID, 500 PRICE FROM DUAL
UNION ALL
SELECT 4 PRODUCT_ID, 3 TYPE_ID, 2000 PRICE FROM DUAL
UNION ALL
SELECT 1 PRODUCT_ID, 4 TYPE_ID, 1000 PRICE FROM DUAL
UNION ALL
SELECT 2 PRODUCT_ID, 5 TYPE_ID, 1500 PRICE FROM DUAL
UNION ALL
SELECT 3 PRODUCT_ID, 2 TYPE_ID, 500 PRICE FROM DUAL
UNION ALL
SELECT 2 PRODUCT_ID, 3 TYPE_ID, 2000 PRICE FROM DUAL
)
SELECT * FROM
(SELECT PRODUCT_ID, TYPE_ID, SUM(PRICE) TOTAL FROM INPUT_LIST GROUP BY PRODUCT_ID, TYPE_ID)
PIVOT (SUM(TOTAL) FOR TYPE_ID IN (1 AS "FIRST_TYPE", 2 AS "SECOND_TYPE", 3 AS "THIRD_TYPE", 4 AS "FOURTH_TYPE", 5 AS "FIFTH"))
ORDER BY PRODUCT_ID;

多值意味着我想将TYPE_ID in (3,4,5)标记为“OTHER_TYPE”。类似的东西:

PIVOT (SUM(TOTAL) FOR TYPE_ID IN (1 AS "FIRST_TYPE", 2 AS "SECOND_TYPE", (3,4,5) AS "OTHER_TYPE"))

我可以使用其他方式进行查询,但我想知道可以使用pivot吗?

2 个答案:

答案 0 :(得分:1)

没有PIVOT条款没有这样的功能 但你仍然可以采用老式的方式:

List<Locations> coords = await locationTable.Where(u => u.fk_company_id == viewModel.UserData.fk_company_id).ToListAsync();
List<LatLongs> latLongs = coords.Select(c => new LatLongs
  {
      latlongs = JsonConvert.DeserializeObject<List<LatLong>>(c.geofence_coordinates)
  }).ToList();

答案 1 :(得分:1)

首先将子查询中的类型分组:

SELECT *
FROM   (
  SELECT PRODUCT_ID, 
         CASE
           WHEN TYPE_ID IN (1,2)
           THEN TYPE_ID
           ELSE 3
         END AS TYPE_ID,
         PRICE
  FROM   INPUT_LIST
)
PIVOT (
  SUM(PRICE) FOR TYPE_ID IN (
    1 AS "FIRST_TYPE",
    2 AS "SECOND_TYPE",
    3 AS "OTHER_TYPE"
  )
)
ORDER BY PRODUCT_ID;