2017-09-16 246 views
-1

我已經看到了類似的問題,但由於我的數據存儲方式,我不確定如何去解決這個問題。在mySQL中獲取每月/每月的月/月銷售額

銷售表:

... | price | amount | weight | special | purchase_date | ... 
  • 價爲每股1倍量或1磅
  • 如果一個項目是由英鎊收取的金額爲null成本。
  • 如果某件物品不是由英鎊收費,則重量爲空。
  • 如果沒有任何或x/y,則特殊值爲null,例如,總共$ 3的2被存儲爲「2/3」。如果該項目按金額收費,則只能有一個特殊情況。當物品有特殊物品時,這意味着物品以特價出售。所以應該計算成本(金額/ x)* y。

我想白天和每月能拿到利潤總額(2個獨立的查詢)

現在忽略特價和用於獲取每月利潤,我想:

select month(purchase_date) as month, sum(price * amount) as profit 
from sales 
where special is null and weight is null 
group by month(purchase_date) 

union 

select month(purchase_date) as month, sum(price * weight) as profit 
from sales 
where special is null and amount is null 
group by month(purchase_date) 

我米不知道我有什麼是接近的,但我有點困惑於工作組如何,所以我不知道如何計算正確的答案。

編輯: 增加了有關特殊應該如何工作的細節。

+0

是您的特色字段是VARCHAR還是INT?該字段的值將採用格式x/y? –

+0

它是一個VARCHAR。是x/y是格式。對困惑感到抱歉。 – Apickle

+0

好的。我編輯了我的答案。希望它有效。 –

回答

0

試試這個:

這裏SUBSTRING_INDEX(SUBSTRING_INDEX(specials, '/', 1), '/', -1)功能將在x/y格式分割數據成xy seperately然後CONVERT()函數會將VARCHAR數據類型轉換爲DECIMAL值進行計算。

MONTHNAME函數會將月份值轉換爲月份名稱。

SELECT MONTHNAME(purchase_date) AS Month, 
    SUM(CASE WHEN weight IS NULL THEN 
       CASE WHEN special IS NULL THEN price*amount 
          ELSE amount/CONVERT(SUBSTRING_INDEX(SUBSTRING_INDEX(special, '/', 1), '/', -1),DECIMAL(10,2)) * CONVERT(SUBSTRING_INDEX(SUBSTRING_INDEX(special, '/', 2), '/', -1),DECIMAL(10,2)) END 
      WHEN amount IS NULL THEN price*weight 
    END) AS Profit 
FROM sales 
GROUP BY MONTHNAME(purchase_date) 
0

試試這個。它不需要使用聯合。

SELECT 
    MONTH(`purchase_date`) AS `month`, 
    SUM(IF(`amount` IS NULL,`price` * `weight`,`price` * `amount`)) as `profit` 
FROM `sales` 
GROUP BY month(`purchase_date`); 
0

你也可以有一個單一的查詢。當您使用SUM()之類的聚合函數時,GROUP BY用於按您指定的列獲取記錄集合。

SELECT month(purchase_date) AS month, 
     SUM(CASE WHEN weight IS NULL 
       THEN price * amount 
       WHEN amount is null 
       THEN price * weight 
      END) profit 
    FROM sales 
WHERE special IS NULL 
    AND (amount IS NULL OR weight IS NULL) 
GROUP BY month(purchase_date) 
0

管理3個選項時可以使用CASE。 (第三選項是不明確所以已指定其爲2/3)

select 
      month(purchase_date) as month, 
      sum(case when amount is null then price * weight 
       when weight is null then price * weight 
       when special is null then 2/3 
       end) as profit 
    from sales 
    group by month(purchase_date)