SQL查询生成以下输出

时间:2017-07-16 16:46:22

标签: sql

显示用户ID,用户名,总金额,折扣后支付的金额,并将别名命名为User_ID,user_name,Total_amount,Paid_amount。按用户ID降序显示记录。点击TABLE SHCEMA获取表格

这是我写的代码。但这并没有显示出预期的结果:

SELECT 
    USERS.USER_ID AS User_ID,
    NAME AS user_name,
    (FARE * NO_SEATS) AS Total_amount 
FROM 
    USERS 
INNER JOIN 
    TICKETS ON USERS.USER_ID = TICKETS.USER_ID 
INNER JOIN 
    PAYMENTS ON TICKETS.TICKET_ID = PAYMENTS.TICKET_ID 
INNER JOIN 
    DISCOUNTS ON PAYMENTS.DISCOUNT_ID = DISCOUNTS.DISCOUNT_ID 
GROUP BY 
    USERS.USER_ID, NAME, FARE, NO_SEATS
ORDER BY 
    USERS.USER_ID DESC;

这是预期的输出:

USER_ID USER_NAME   TOTAL_AMOUNT   PAID_AMOUNT
----------------------------------------------
 5       Krena           700         625
 4       Johan           800         775
 3       Ivan           3000        2900
 1       John           4000        3950
 1       John           4000        3950
 1       John           2000        1900

5 个答案:

答案 0 :(得分:0)

试试这段代码。

SELECT 
USERS.USER_ID AS USER_ID,
USERS.NAME AS USER_NAME,
(TICKETS.FARE * TICKETS.NO_SEATS) AS TOTAL_AMOUNT,
(TICKETS.FARE * DISCOUNTS.DISCOUNT_AMOUNT) + TICKETS.FARE AS PAID_AMOUNT 
FROM 
USERS USERS
INNER JOIN TICKETS TICKETS
        ON USERS.USER_ID=TICKETS.USER_ID 
INNER JOIN PAYMENTS PAYMENTS
        ON TICKETS.TICKET_ID=PAYMENTS.TICKET_ID 
INNER JOIN DISCOUNTS DISCOUNTS
        ON PAYMENTS.DISCOUNT_ID=DISCOUNTS.DISCOUNT_ID 
ORDER BY USERS.USER_ID DESC;

我在数据库结构中感到困惑,为什么它在数字数据类型中呢?您可能想要将其更改为十进制,并将其长度设置为(11,2),因为我假设您的折扣金额中的折扣金额是百分比吗?或者只是将示例数据库粘贴到此处,以便我可以更新我的代码。

答案 1 :(得分:0)

如果我有足够的声誉,我会把它写成评论(叹息): 你还没有明确定义你的预期结果。

我假设以下内容:

  • 打印用户的总金额,包括Total_amount(即官方价格),Paid_amount(即折扣后),因此它将包括所有门票及其付款。
  • 我认为折扣是从展会上扣除的正数,是每1个席位

那么这应该可以解决问题:

SELECT 
  USER_ID AS USER_ID,
  NAME AS USER_NAME,
  sum(FARE * NO_SEATS) AS TOTAL_AMOUNT,
  sum((FARE - DISCOUNT_AMOUNT ) * NO_SEATS) AS PAID_AMOUNT 
FROM USERS u
INNER JOIN TICKETS t
        ON u.USER_ID=t.USER_ID 
INNER JOIN PAYMENTS p
        ON t.TICKET_ID=p.TICKET_ID 
INNER JOIN DISCOUNTS d
        ON p.DISCOUNT_ID=d.DISCOUNT_ID 
group by USER_ID, name
ORDER BY USER_ID DESC;

答案 2 :(得分:0)

这将有效,请尝试

SELECT 
USERS.USER_ID AS USER_ID,
USERS.NAME AS USER_NAME,
(TICKETS.FARE * TICKETS.NO_SEATS) AS TOTAL_AMOUNT,
(TICKETS.FARE * TICKETS.NO_SEATS - DISCOUNTS.DISCOUNT_AMOUNT) AS PAID_AMOUNT 
FROM 
USERS 
INNER JOIN TICKETS 
        ON USERS.USER_ID=TICKETS.USER_ID 
INNER JOIN PAYMENTS
        ON TICKETS.TICKET_ID=PAYMENTS.TICKET_ID 
INNER JOIN DISCOUNTS
        ON PAYMENTS.DISCOUNT_ID=DISCOUNTS.DISCOUNT_ID 
ORDER BY USERS.USER_ID DESC;

答案 3 :(得分:0)

这是该问题的正确答案,可以给出准确的输出结果

use-attribute-sets

答案 4 :(得分:-2)

将查询写入

显示用户ID,用户名,票证ID,总金额,待付款金额 折扣后付款,并给别名提供用户名,用户名, 票证编号,总金额,已付款金额。以降序显示记录 按用户ID排序。

避免重复记录。

[注意:要支付的总金额应为机票数量*每张机票的金额]

此代码运行100%

enter image description here