2017-07-03 68 views
0

在「書籍」類別中可用的所有產品中,過去3個月訂購的百分比是多少?查找已訂購產品的百分比

ORDERS 
order_id 
customer_id 
order_date 
product_id 

PRODUCTS 
product_id 
product_name 
product_category 
product_price 

回答

0

我假設你在計數器百分比後。如果你想比較值,你需要稍微改變一下選擇。 下面是我將如何做到這一點。請注意,我沒有運行它,所以你可能有一些語法錯誤,但應該很容易解決它們。

WITH books AS (
    SELECT order_date 
    FROM orders 
    JOIN products 
     ON orders.product_id = products.product_id 
    WHERE products.product_category = 'books' 
), 
last_three_months AS (
    SELECT 0 as counter_1, count(*) AS counter_2 
    FROM books 
    WHERE order_date > DATEADD(MONTH, -3, GETDATE()); 
), 
total_orders AS (
    select count(*) AS counter_1, 0 as counter_2 
    FROM books 
), 
all_together AS (
SELECT counter_1, counter_2 
    FROM last_three_months 
UNION ALL 
SELECT counter_1, counter_2 
    FROM total_orders 
), 
sale_sums AS (
    SELECT SUM(counter_2) AS counter_2, SUM(counter_1) AS counter_1 
    FROM all_together 
) 
SELECT counter_2/counter_1 * 100 
FROM sale_sums 
0

試試這個簡單的查詢。這是一個簡單的PSQL。學習簡單的語法,你就可以自己完成。

WITH ordersLastThree as 
(
Select o.* FROM PRODUCTS p,ORDERS o where p.product_id=o.product_id and 
p.product_category = [Books product_category] 
and o.order_date >= DATEADD(MONTH, -3, GETDATE()) 
) 
Select (ISNULL((Select count(*) from ordersLastThree),1)*100)/count(o.*) as Result 
FROM PRODUCTS p,ORDERS o where p.product_id=o.product_id and 
p.product_category = [Books product_category] 
0

首先你必須告訴我們您正在使用然後將數據基地。

它會相應VARRY .. 如果MySQL和C#fornt結束那麼代碼wiil

.. ..將sql查詢返回的行接收到daatareader然後應用計算。我希望它清楚你的疑問

相關問題