SQL Select语句查询

时间:2013-11-21 14:25:57

标签: sql-server select join sql

这些是我正在使用的创建表:

create table Customer2 (cid char(3), cname char(10), primary key (Cid)); 

create table Employee2 
(
     eid char(3), ename char(10), salary number(7,2), 
     mid char(3), 
     primary key (eid), foreign key (mid) references Employee2
); 

create table ArtObject2 
(
      aoid char(3), atitle char(12), artist varchar(10), pricea number(8,2), 
      primary key (aoid)
); 

create table MakesD2 
(
     aoid char(3), eid char(3), cid char(3), prices number, dates date, 
     primary key (aoid, CID), 
     foreign key (aoid) references ArtObject2, 
     foreign key (CID) references Customer2, 
     foreign key (eid) references Employee2
);

我需要编写以下SQL语句:

  1. 找到购买数量最多的客户的名字。
  2. 查找在1-JUL-12之后购买多件油画的客户
  3. 为每幅画卖出展示画作的标题,由客户支付的价格 和#34;高于平均水平"如果这幅画的售价高于平均要价和“低于平均水平”的话。如果这幅画是出售的 价格低于平均要价。对于包含单词"高于的列 问"或者"低于要求"标题备注。
  4. 我为#1尝试了这个声明,但没有奏效:

    select cname 
    from customer2 
    where cid in 
          (select cid 
           from makesd2 
           where prices >=ALL(select prices from makesd2 group by cname)
          );
    

    我为#2尝试了这个声明但没有返回所有结果:

    select cname 
    from customer2 
    where cid in
          (select cid 
           from makesd2 
           where dates > '1-JUL-12' 
           group by cid 
           having count(cid) > 1);
    

    任何帮助将不胜感激。感谢

1 个答案:

答案 0 :(得分:0)

1:您必须制作子查询以获取每个客户购买的绘画数量,并使用customer2表格加入以获取客户的姓名:

SELECT c.cname
FROM Customer2 c
INNER JOIN (
  SELECT cid,
    COUNT(*) AS bought
  FROM makesd2
  GROUP BY cid
  ) m ON m.cid = c.cid
ORDER BY m.bought

2:与上面相同,但是在这一篇中,你会发现自那个日期以来买了不止一幅画的cid是什么:

SELECT c.cname
FROM Customer2 c
INNER JOIN (
  SELECT cid,
    COUNT(*) AS bought
  FROM makesd2
  WHERE dates > '1-JUL-12'
  GROUP BY cid
  HAVING COUNT(*) > 1
  ) m ON m.cid = c.cid

3:这个是CASE的简单用法:

SELECT a.atitle,
  m.prices,
  CASE 
    WHEN m.aprice > (SELECT AVG(prices) FROM MakesD2)
      THEN 'Higher than average'
    ELSE 'Lower than average'
  END AS averageRating
FROM MakesD2 m
INNER JOIN ArtObject2 a ON a.aoid = m.aoid