嗨,我有一张表格,其中包含以下字段:godwon、产品名称、数量我想获得结果仓库和产品明智请检查图片
记住仓库不能修复它取决于用户可能 2 个仓库或 100 个仓库
嗨,我有一张表格,其中包含以下字段:godwon、产品名称、数量我想获得结果仓库和产品明智请检查图片
记住仓库不能修复它取决于用户可能 2 个仓库或 100 个仓库
那么解决方案取决于数据 - 您是否只有 6 个“货仓”值?如果是这样,您可以尝试以下解决方案:
CREATE TABLE my_table (
godown VARCHAR2(20),
product_name VARCHAR2(20),
quantity NUMBER
);
INSERT INTO my_table VALUES ('Godown1', 'Rice', 5);
INSERT INTO my_table VALUES ('Godown1', 'Tea', 6);
INSERT INTO my_table VALUES ('Godown1', 'Milk', 4);
INSERT INTO my_table VALUES ('Godown2', 'Rice', 6);
INSERT INTO my_table VALUES ('Godown2', 'Tea', 7);
INSERT INTO my_table VALUES ('Godown2', 'Milk', 5);
INSERT INTO my_table VALUES ('Godown3', 'Rice', 8);
INSERT INTO my_table VALUES ('Godown3', 'Tea', 3);
INSERT INTO my_table VALUES ('Godown3', 'Milk', 5);
INSERT INTO my_table VALUES ('Godown4', 'Rice', 3);
INSERT INTO my_table VALUES ('Godown4', 'Tea', 2);
INSERT INTO my_table VALUES ('Godown4', 'Milk', 1);
INSERT INTO my_table VALUES ('Godown5', 'Rice', 4);
INSERT INTO my_table VALUES ('Godown5', 'Tea', 6);
INSERT INTO my_table VALUES ('Godown5', 'Milk', 7);
INSERT INTO my_table VALUES ('Godown6', 'Rice', 9);
INSERT INTO my_table VALUES ('Godown6', 'Tea', 24);
INSERT INTO my_table VALUES ('Godown6', 'Milk', 12);
COMMIT;
SELECT
product_name,
godown1_sum_quantity AS Godown1,
godown2_sum_quantity AS Godown2,
godown3_sum_quantity AS Godown3,
godown4_sum_quantity AS Godown4,
godown5_sum_quantity AS Godown5,
godown6_sum_quantity AS Godown6,
(SELECT SUM(quantity) FROM my_table WHERE product_name = data.product_name) AS Total
FROM (
SELECT
product_name,
godown,
quantity
FROM my_table
)
PIVOT (SUM(quantity) AS sum_quantity
FOR (godown) IN (
'Godown1' AS Godown1,
'Godown2' AS Godown2,
'Godown3' AS Godown3,
'Godown4' AS Godown4,
'Godown5' AS Godown5,
'Godown6' AS Godown6
)
) data
;
检查 SQLFiddle:http ://sqlfiddle.com/#!4/5f8e8/1
您可以将 CASE 语句与聚合函数一起使用。
SELECT product_name,
MIN (CASE WHEN godown = 'godown1' THEN quantity END) godown1,
MIN (CASE WHEN godown = 'godown2' THEN quantity END) godown2,
MIN (CASE WHEN godown = 'godown3' THEN quantity END) godown3,
MIN (CASE WHEN godown = 'godown4' THEN quantity END) godown4,
MIN (CASE WHEN godown = 'godown5' THEN quantity END) godown5,
MIN (CASE WHEN godown = 'godown6' THEN quantity END) godown6,
SUM (quantity)
FROM products
GROUP BY product_name;
您也可以在 11g 中使用 PIVOT 运算符,但它不会为您提供最终的总计列。您必须单独计算。
SELECT *
FROM (SELECT godown, product_name, quantity FROM products)
PIVOT (MIN (
quantity)
FOR (godown)
IN ('godown1' AS godown1,
'godown2' AS godown2,
'godown3' AS godown3,
'godown4' AS godown4,
'godown5' AS godown5,
'godown6' AS godown6));