如何在sqlite3中获取小数长度为3的列的值?

问题描述 投票:0回答:1

这里

我试图将一列的值除以另一列,并将结果放入新列中,四舍五入到千位。蒂亚!

这是我尝试过的代码:

%%sql
--#WHICH 5 CASHIERS RANG UP THE MOST CUSTOMERS ON AVERAGE PER SHIFT?
WITH customers_seen AS (SELECT E.NAME,
                               E.EMPLOYEE_ID,
                               E.POSITION,
                               COUNT(DISTINCT T.TRANSACTION_ID) AS CUSTOMERS_SERVICED,
                               S.STORE_BRANCH
                        FROM TRANSACTIONS T
                        JOIN EMPLOYEES E
                        ON E.EMPLOYEE_ID = T.CASHIER_ID
                        JOIN STORES S
                        ON S.STORE_ID = T.STORE_ID
                        GROUP BY E.NAME
                        ORDER BY CUSTOMERS_SERVICED DESC),

number_of_shifts AS (SELECT E.NAME,
                            E.EMPLOYEE_ID,
                            COUNT(DISTINCT T.DATE) AS NUMBER_OF_SHIFTS,
                            E.SHIFT,
                            E.POSITION
                     FROM TRANSACTIONS T
                     JOIN EMPLOYEES E
                     ON E.EMPLOYEE_ID = T.CASHIER_ID
                     GROUP BY E.NAME
                     HAVING E.POSITION = 'cashier'
                     ORDER BY NUMBER_OF_SHIFTS DESC)

SELECT n.NAME,
       c.CUSTOMERS_SERVICED,
       n.NUMBER_OF_SHIFTS,
       ROUND(printf("%.1f",c.CUSTOMERS_SERVICED/n.NUMBER_OF_SHIFTS),4) AS CUSTOMERS_SERVICED_PER_SHIFT
FROM number_of_shifts n
JOIN customers_seen c
ON n.EMPLOYEE_ID = c.EMPLOYEE_ID
ORDER BY CUSTOMERS_SERVICED_PER_SHIFT DESC
LIMIT 5;

我得到这个值是四舍五入的结果: enter image description here

sql sqlite decimal
1个回答
0
投票

我相信你的问题是你对格式化(printf'ed)输出进行舍入,从而丢失了尾随的 0。

尝试一下

printf('%.3f',c.CUSTOMERS_SERVICED/n.NUMBER_OF_SHIFTS))

也许考虑以下示例:-

DROP TABLE IF EXISTS ex;
CREATE TABLE IF NOT EXISTS ex (col1 REAL);
INSERT INTO ex VALUES (1234567.1234567),(7654321.7654321),(654321.654321),(54321.54321),(366 * 500);
SELECT *,
    /* Premature rounding*/
    ROUND(printf('%.3f',col1 / 366),3) AS ex01,
    ROUND(printf('%.3f',col1),4) AS ex02,
    /* pre formatting explicit rounding */
    printf('%.3f',round(col1),3) AS ex03,
    printf('%.3f',round(col1/366),3) AS ex04,
    /* pre formatting implicit rounding by printf */
    printf('%.3f',col1/366,3) AS ex05,
    printf('%.3f',col1/366.1234) AS ex06,
    printf('%.9f',col1/366.1234) AS ex07
FROM ex;
DROP TABLE IF EXISTS ex;

这会导致:-

和:-

  1. ex01 和 ex02 不是四舍五入到整数所要求的
  2. ex03 和 ex04 舍入为整数,但格式为 3 dp
  3. ex05 和 ex06 四舍五入为 3dp
  4. ex07 显示 ex06 后面的值到 9dp(以确认舍入)
© www.soinside.com 2019 - 2024. All rights reserved.