用SQL除数

时间:2019-05-31 19:47:42

标签: sql

我有一个包含产品订单的数据库,我需要将男性订单除以每年的所有订单。

我成功地打印了每年的所有订单和每年的男士订单,但是我不知道如何显示将数字相除的数字。

SELECT 
    YEAR(o.Order_Date) AS year,
    COUNT(o.order_id) AS number_of_orders
FROM
    [targil 2].[dbo].[exc2 - product] p, [targil 2].[dbo].[exc2 - orders] o
WHERE 
    p.Product_ID = o.Product_ID 
GROUP BY
    YEAR(o.Order_Date);

输出=

   year    number_of_orders
   -------------------------
   2012        540
   2013        512
   2014        180

SELECT DISTCINT
    YEAR(o.Order_Date) AS year, 
    COUNT(o.order_id) AS number_of_orders
FROM
    [targil 2].[dbo].[exc2 - product] p, [targil 2].[dbo].[exc2 - orders] o
WHERE 
    p.Product_ID = o.Product_ID 
    AND p.Product_Name LIKE '%men%'
GROUP BY
    YEAR(o.Order_Date);

输出

year  number_of_orders
----------------------
2012       50
2013      146
2014      138

所需的输出

year   number_of_men_orders_of_all_orders
----------------------------------------
2012        0.0925
2013        0.285
2014        0.766

2 个答案:

答案 0 :(得分:1)

您使用的是哪种SQL?看起来像MS Sql Server。

您必须将自己年份的两个结果集合并在一起,以便可以比较每个结果集的计数。尝试这样的事情:

WITH all_orders AS (
    SELECT YEAR(Order_Date) 'Year', COUNT(*) 'Count'
    FROM [targil 2].[dbo].[exc2 - orders]
    GROUP BY YEAR(Order_Date)
), men_orders AS (
    SELECT YEAR(o.Order_Date) 'Year', COUNT(*) 'Count'
    FROM [targil 2].[dbo].[exc2 - orders] o
    JOIN [targil 2].[dbo].[exc2 - product] p
        ON p.Product_ID = o.Product_ID
    WHERE p.Product_Name LIKE '%men%'
    GROUP BY YEAR(o.Order_Date)
)
SELECT
    COALESCE(a.Year, m.Year) 'Year',
    a.Count 'All Count',
    m.Count 'Men Count',
    CAST(ISNULL(m.Count, 0) AS DECIMAL) / CAST(a.Count AS DECIMAL) 'Ratio'
FROM all_orders a
LEFT JOIN men_orders m ON m.Year = a.Year

答案 1 :(得分:0)

使用条件聚合!并学习使用正确,明确,标准 ... "serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "app:build", "host": "0.0.0.0" ... 语法

WARNING: This is a simple server for use in testing or debugging Angular applications
locally. It hasn't been reviewed for security issues.

Binding this server to an open connection can result in compromising your application or
computer. Using a different host than the one passed to the "--host" flag might result in
websocket connection issues. You might need to use "--disableHostCheck" if that's the
case.