我试图写一个SQL查询来解决www.sql-ex.ru(问题28)中的问题,我得到了正确的结果,但是我收到了这个错误"你的查询失败了在第三个检查数据库。"
SQL查询问题:
在两位小数之内,定义每平方油漆的平均数量。
SQL备注:
数据库模式由3个表组成:
utQ(Q_ID int,Q_NAME varchar(35)),utV(V_ID int,V_NAME varchar(35),V_COLOR char(1)),
utB(B_Q_ID int,B_V_ID int,B_VOL tinyint,B_DATETIME datetime)。 表utQ包括方形标识符,方形名称。请注意,非彩绘方块为黑色。
utV包括气球标识符,气球名称和颜色。 表格utB显示了绘画方块与绘画气球的信息,包括方形标识符,气球标识符,绘画数量和绘画时间。
- 应该注意,气球可以是三种颜色中的一种:红色(V_COLOR =' R'),绿色(V_COLOR =' G')或蓝色(V_COLOR = ' B&#39);
- 任何气球最初已满,体积为255;
- 方形颜色根据RGB规则定义,即R = 0,G = 0,B = 0为黑色,而R = 255,G = 255,B = 255为白色;
- 表格中的任何记录utB都会通过B_VOL减少气球中的油漆数量,并将方块中的油漆数量增加相同的值;
- B_VOL必须大于0且小于或等于255;
- 一个方格中相同颜色的涂料数量不得超过255;
- 气球中的油漆量不得少于0;
- 绘画时间(B_DATETIME)在一秒钟内给出,即它不包含毫秒。
方案
我的代码
WITH x AS (SELECT b_q_id, b_v_id, ball.v_color, b_vol as vol FROM utb
JOIN utv ball
ON utb.b_v_id = ball.v_id)
, y AS (
SELECT b_q_id, v_color, totalcolor = CASE WHEN SUM(vol) > 255 THEN 255
ELSE SUM(vol) END FROM x
GROUP BY b_q_id, v_color),
z AS(
SELECT b_v_id, totalbcolor =
CASE WHEN SUM(b_vol) > 255 THEN 255
ELSE SUM(b_vol)
END
FROM utb
GROUP BY b_v_id)
, a AS
(SELECT b_q_id, SUM(totalcolor) totalacolor FROM y GROUP BY b_q_id)
, b AS
(SELECT b_q_id,b_v_id, totalacolor FROM a, z)
, c AS
(SELECT DISTINCT b.b_q_id, totalacolor FROM b
INNER JOIN utb
ON (b.b_q_id = utb.b_q_id AND b.b_v_id = utb.b_v_id))
SELECT
CAST(CAST(SUM(totalacolor) AS NUMERIC(8,2))
/ (SELECT COUNT(*) FROM utq)AS NUMERIC(8,2))
FROM c
正确答案
386.25
评论 我的代码可能过长了。但是,可能有一种更短的方式。但是,我仍然没有找到我错的地方。请帮忙。
答案 0 :(得分:5)
这里是你的代码)
SELECT CONVERT(NUMERIC(15,2),SUM(COALESCE(UB.B_VOL,0)) / CONVERT(FLOAT,COUNT(DISTINCT UQ.Q_ID)))
FROM utQ AS UQ
LEFT JOIN utB AS UB ON UQ.Q_ID = UB.B_Q_ID
LEFT JOIN utV AS UV ON UB.B_V_ID = UV.V_ID
以下测试
答案 1 :(得分:0)
如果您想要与帮助主题一起使用,可以使用此查询:
SELECT cast(SUM(case when UB.B_VOL IS NULL then 0 else UB.B_VOL end) /cast(COUNT(DISTINCT UQ.Q_ID) as float) as decimal(8,2))FROM utQ AS UQ
LEFT JOIN utB AS UB ON UQ.Q_ID = UB.B_Q_ID
答案 2 :(得分:0)
这是另一种解决方案,使用CASE WHEN ... THEN ... ELSE ... END
:
SELECT CONVERT(NUMERIC(15,2),
(
SELECT SUM(total_paint) * 1.0 / COUNT(Q_ID) AS avg_paint
FROM
(
SELECT DISTINCT utQ.Q_ID,
CASE
WHEN SUM(B_VOL) IS NULL
THEN 0
ELSE SUM(B_VOL)
END
AS total_paint
FROM utQ
LEFT JOIN utB ON utB.B_Q_ID = utQ.Q_ID
GROUP BY utQ.Q_ID
) AS tmp
)
)