讓我們試試這種方式。你可以看到,我有很多SELECT(我只顯示3個,但我有20個以上),我需要統一所有這些。每當我需要添加品牌時,我都必須逐個更改所有的SELECT。這很無聊。SQL:While和Union統一SELECTs
此外,我有超過10個品牌(不僅3),我也需要一個一個地打字。如果我可以只改變一次,並且讓WHILE LOOP爲其他SELECT執行剩餘操作,那麼這並不是那麼糟糕。但是,如果我必須更換所有SELECT的所有品牌,這需要我很多時間。
DECLARE @COUNTRY varchar(30)
SET @COUNTRY = 'GERMANY'
SELECT * FROM
(SELECT * FROM
(SELECT
FOOD_CATEGORY,
YEAR_SALE,
CASE WHEN SUM(SALES)=0 THEN 0
ELSE ROUND(SUM(CASE WHEN FABRICANTE='BRAND A' THEN ROUND(SALES,3) ELSE 0 END)/SUM(SALES),3)
END AS Share_A,
CASE WHEN SUM(SALES)=0 THEN 0
ELSE ROUND(SUM(CASE WHEN FABRICANTE='BRAND B' THEN ROUND(SALES,3) ELSE 0 END)/SUM(SALES),3)
END AS Share_B,
CASE WHEN SUM(SALES)=0 THEN 0
ELSE ROUND(SUM(CASE WHEN FABRICANTE='BRAND C' THEN ROUND(SALES,3) ELSE 0 END)/SUM(SALES),3)
END AS Share_C
FROM tableChicken
WHERE
AREA = @COUNTRY
GROUP BY
FOOD_CATEGORY,
YEAR_SALE) AS CHICKEN
UNION
SELECT * FROM
(SELECT
FOOD_CATEGORY,
YEAR_SALE,
CASE WHEN SUM(SALES)=0 THEN 0
ELSE ROUND(SUM(CASE WHEN FABRICANTE='BRAND A' THEN ROUND(SALES,3) ELSE 0 END)/SUM(SALES),3)
END AS Share_A,
CASE WHEN SUM(SALES)=0 THEN 0
ELSE ROUND(SUM(CASE WHEN FABRICANTE='BRAND B' THEN ROUND(SALES,3) ELSE 0 END)/SUM(SALES),3)
END AS Share_B,
CASE WHEN SUM(SALES)=0 THEN 0
ELSE ROUND(SUM(CASE WHEN FABRICANTE='BRAND C' THEN ROUND(SALES,3) ELSE 0 END)/SUM(SALES),3)
END AS Share_C
FROM tableSwine
WHERE
AREA = @COUNTRY
GROUP BY
FOOD_CATEGORY,
YEAR_SALE) AS SWINE
UNION
SELECT * FROM
(SELECT
FOOD_CATEGORY,
YEAR_SALE,
CASE WHEN SUM(SALES)=0 THEN 0
ELSE ROUND(SUM(CASE WHEN FABRICANTE='BRAND A' THEN ROUND(SALES,3) ELSE 0 END)/SUM(SALES),3)
END AS Share_A,
CASE WHEN SUM(SALES)=0 THEN 0
ELSE ROUND(SUM(CASE WHEN FABRICANTE='BRAND B' THEN ROUND(SALES,3) ELSE 0 END)/SUM(SALES),3)
END AS Share_B,
CASE WHEN SUM(SALES)=0 THEN 0
ELSE ROUND(SUM(CASE WHEN FABRICANTE='BRAND C' THEN ROUND(SALES,3) ELSE 0 END)/SUM(SALES),3)
END AS Share_C
FROM tableTurkey
WHERE
AREA = @COUNTRY
GROUP BY
FOOD_CATEGORY,
YEAR_SALE) AS TURKEY
) AS MAIN_BASE
ORDER BY FOOD_CATEGORY, YEAR_SALE
我希望現在可以理解。感謝您的幫助!
你的數據庫是mysql還是sql-server? –