大单位,小单位问题
我有两张表,一张产品表,一张单位表;
现在产品表里有两个单位,而且存的是主键ID,
怎样同时提取两个单位的名称?
测试数据如下:
IF EXISTS(SELECT name
FROM sysobjects
WHERE name = N 'Unit '
AND type = 'U ')
DROP TABLE Unit
GO
CREATE TABLE Unit (
UnitID INT IDENTITY(1,1) PRIMARY KEY ,
UnitName CHAR(50) NOT NULL,
)
GO
IF EXISTS(SELECT name
FROM sysobjects
WHERE name = N 'Product '
AND type = 'U ')
DROP TABLE Product
GO
CREATE TABLE Product (
ProductID INT IDENTITY(1,1) PRIMARY KEY ,
ProductName CHAR(50) NOT NULL,
BigUnit INT NOT NULL FOREIGN KEY REFERENCES Unit(UnitID),
SmallUnit INT NOT NULL FOREIGN KEY REFERENCES Unit(UnitID)
)
GO
INSERT INTO Unit VALUES( '盒 ')
INSERT INTO Unit VALUES( '支 ')
INSERT INTO Product VALUES( 'XP001 ',1,2)
INSERT INTO Product VALUES( 'XP002 ',1,2)
INSERT INTO Product VALUES( 'XP003 ',1,2)
INSERT INTO Product VALUES( 'XP004 ',1,2)
INSERT INTO Product VALUES( 'XP005 ',1,2)
//-------------------------------------------------
//能得到如下结果即可。
ProductID ProductName BigUnit SmallUnit
----------- ------------- ----------- -----------
1 XP001 盒 支
2 XP002 盒 支
3 XP003 盒 支
4 XP004 盒 支
5 XP005 盒 支
------解决方案--------------------select
a.ProductID,
a.ProductName,
max(case a.BigUnit