当Distinct不起作用时,删除查询中的重复值? SQL

时间:2018-02-24 14:12:35

标签: sql

这是我正在运行的当前查询。

select c.customer_name, c.city, c.credit_limit, sum(ol.quoted_price)
from   customer c, order_line ol, (select order_num from order_line where part_num = 'AT94') t1
where ol.order_num = t1.order_num and customer_num in ( select customer_num
    from orders
    where order_num in (select t1.order_num
         from order_line,(select order_num from order_line where part_num = 'AT94') t1
         INNER JOIN 
         (select order_num from order_line where part_num = 'BV06') t2
         on t1.order_num = t2.order_num
         where t1.order_num = order_line.order_num
         group by t1.order_num))
group by t1.order_num, c.customer_name, c.city, c.credit_limit

我收到的当前输出是:

enter image description here

我希望显然删除输出中的重复内容,目前不知道如何操作。我尝试在多个子查询中使用unique,但没有成功。

任何帮助都很棒!感谢。

这是数据库创建。

CREATE TABLE CUSTOMER
(
   CUSTOMER_NUM CHAR(3) PRIMARY KEY,
   CUSTOMER_NAME CHAR(35) NOT NULL,
   STREET CHAR(15),
   CITY CHAR(15) DEFAULT 'Ottawa',
   PROVINCE CHAR(3),
   ZIP CHAR(5),
   BALANCE DECIMAL(8,2),
   CREDIT_LIMIT DECIMAL(8,2),
   REP_NUM CHAR(2) 
   CONSTRAINT CHK_Limit CHECK (CREDIT_LIMIT >= BALANCE)
);

CREATE TABLE ORDERS
(
   ORDER_NUM CHAR(5) PRIMARY KEY,
   ORDER_DATE DATE,
   CUSTOMER_NUM CHAR(3) 
);

CREATE TABLE PART
(
   PART_NUM CHAR(4) PRIMARY KEY,
   DESCRIPTION CHAR(15),
   ON_HAND DECIMAL(4,0),
   CLASS CHAR(2),
   WAREHOUSE CHAR(1),
   PRICE DECIMAL(6,2) 
);

CREATE TABLE ORDER_LINE
(
   ORDER_NUM CHAR(5),
   PART_NUM CHAR(4),
   NUM_ORDERED DECIMAL(3,0),
   QUOTED_PRICE DECIMAL(6,2),
   PRIMARY KEY (ORDER_NUM, PART_NUM)
);

我想要的解决方案,其中订单与列无关:

Al's.. | Barrhaven | 7500.00  | 21.95
John.. | Toronto   | 10000.00 | 311.95

使用的所有数据。相当多的文字。刚刚决定使用Pastebin而不是更长时间地提出这个问题。

https://pastebin.com/ASBzqcJq

2 个答案:

答案 0 :(得分:0)

我可以看到你的结果集已经有了不同的记录。您的结果集没有任何两行具有完全相同的值。您期望的输出是什么?我不确定你的要求是什么。但我认为缺少Customer表中的客户编号和Orders表中的客户编号之间的连接。 你想做这样的事吗?

select C.customer_name, C.city, C.credit_limit, sum(OL.quoted_price)
from CUSTOMER C 
join ORDERS O ON C.Customer_num=O.Customer_num
join ORDER_LINE OL on O.Order_num=Ol.Order_num
WHERE part_num in('AT94','BV06')
group by  C.customer_name, C.city, C.credit_limit;

enter image description here

答案 1 :(得分:0)

您基本上需要查看哪个客户已经购买了part_numb AT94和BV06。您遇到的问题是您的查询返回重复的行,这是因为您的查询已经有一些冗余。这使我回过头来手动检查给定结果,以便从您提供的样本中获得正确的结果。

SELECT
    ol.ORDER_NUM, 
    c.customer_name, 
    c.city, 
    c.credit_limit, 
    sum(ol.quoted_price)
FROM #order_line ol
INNER JOIN #Orders o ON  o.order_num = ol.order_num
JOIN (SELECT ORDER_NUM FROM #ORDER_LINE WHERE part_num = 'AT94') t1 ON t1.ORDER_NUM =  o.ORDER_NUM
JOIN (SELECT ORDER_NUM FROM #ORDER_LINE WHERE part_num = 'BV06') t2 ON t2.ORDER_NUM =  o.ORDER_NUM
INNER JOIN #customer c ON c.customer_num = o.customer_num
WHERE 
    ol.ORDER_NUM IN(t1.ORDER_NUM) 
AND ol.ORDER_NUM IN(t2.ORDER_NUM)
GROUP BY
    ol.ORDER_NUM,  
    c.customer_name, 
    c.city, 
    c.credit_limit

SQLFiddle

希望这能节省你的一天