USE Homework250320;
Go
-- 找出工程项目J2使用的各种零件的名称及其数量
SELECT P.PNAME AS 零件名称, SUM(SPJ.QTY) AS 总数量
FROM SPJ
         JOIN P ON SPJ.PNO = P.PNO
WHERE SPJ.JNO = 'J2'
GROUP BY P.PNAME;
Go
-- 找出上海厂商供应的所有零件号码
SELECT DISTINCT SPJ.PNO
FROM SPJ
         JOIN S ON SPJ.SNO = S.SNO
WHERE S.CITY = N'上海';
Go
-- 找出使用上海产的零件的工程名称
SELECT DISTINCT J.JNAME
FROM SPJ
         JOIN S ON SPJ.SNO = S.SNO
         JOIN J ON SPJ.JNO = J.JNO
WHERE S.CITY = N'上海';
Go
-- 找出没有使用天津产的零件的工程号码
SELECT JNO
FROM J
WHERE JNO NOT IN (SELECT DISTINCT SPJ.JNO
                  FROM SPJ
                           JOIN S ON SPJ.SNO = S.SNO
                  WHERE S.CITY = N'天津');
Go
-- 把全部红色零件的颜色改成蓝色
UPDATE P
SET COLOR = N'蓝'
WHERE COLOR = N'红';
SELECT PNO, COLOR
FROM P; -- Validate
Go
-- 将S5供给J4的零件P6改为由S3供应
UPDATE SPJ
SET SNO = 'S3'
WHERE SNO = 'S5'
  AND JNO = 'J4'
  AND PNO = 'P6';
SELECT *
FROM SPJ
WHERE JNO = 'J4'
  AND PNO = 'P6'; -- Validate
Go
-- 删除供应商S2及相关供应记录
DELETE
FROM SPJ
WHERE SNO = 'S2'; -- 先删除SPJ表中S2的供应记录
DELETE
FROM S
WHERE SNO = 'S2'; -- 再删除S表中的S2记录
SELECT SNO
FROM S; -- Validate: S2 已不存在
SELECT SNO
FROM SPJ; -- Validate: S2 相关记录已删除
Go
-- 插入供应情况记录 (S2,J6,P4,200)
INSERT INTO SPJ (SNO, PNO, JNO, QTY)
VALUES ('S2', 'P4', 'J6', 200);
SELECT *
FROM SPJ
WHERE SNO = 'S2'
  AND JNO = 'J6'
  AND PNO = 'P4'; -- Validate
Go