显示来自多个表的数据

时间:2010-06-28 09:59:29

标签: sql-server-2005 tsql

我有3个表(SalesLog,Breakages,SalesReturn),我想显示这些表中的数据,如

ProductName          SalesQty         BreakQty        ReturnQty
ABCD                   1000              10              20

SalesLog表

CREATE TABLE [dbo].[SalesLog](
[SalesID] [int] IDENTITY(1,1) NOT NULL,
[MemoNo] [int] NULL,
[ProductCode] [int] NULL,
[Quantity] [int] NULL,
[Price] [int] NULL,
[pGroup] [int] NULL,
[pName] [nvarchar](30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[pSize] [int] NULL,
[BillDate] [nchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
CONSTRAINT [PK_SalesLog] PRIMARY KEY CLUSTERED 
(
[SalesID] ASC
)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

破损表

CREATE TABLE [dbo].[Breakages](
[breakId] [int] IDENTITY(1,1) NOT NULL,
[MemoNo] [int] NULL,
[SalesmanID] [int] NULL,
[ProductCode] [int] NULL,
[pName] [nvarchar](30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Quantity] [int] NULL,
[pGroup] [nvarchar](20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[BillDate] [nchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[AddedOn] [datetime] NULL,
CONSTRAINT [PK_Breakages_1] PRIMARY KEY CLUSTERED 
(
[breakId] ASC
)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

SalesReturn表

CREATE TABLE [dbo].[SalesReturn](
[srID] [int] IDENTITY(1,1) NOT NULL,
[ProductCode] [int] NULL,
[Quantity] [int] NULL,
[pGroup] [int] NULL,
[MemoNo] [int] NULL,
[SalesmanID] [int] NULL,
[Price] [int] NULL,
[BillDate] [nchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[AddedOn] [datetime] NULL,
CONSTRAINT [PK_SalesReturn] PRIMARY KEY CLUSTERED 
(
[srID] ASC
)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

任何帮助将不胜感激..

2 个答案:

答案 0 :(得分:1)

Select 
      pname as ProductName ,
      ProductCode as pc
      Quantity as SalesQty ,
            (select
                    Quantity 
             from Breakages
             where Breakages.ProductCode = pc
             ) as BreakQty ,
             (select 
                    Quantity 
             from SalesReturn
             where ProductCode = pc) as ReturnQty 
      from SalesLog;

答案 1 :(得分:0)

SELECT
    sl.pName, 
    SUM(sl.Quantity) as TotalQty, 
    SUM(br.Quantity) as TotalBreakageQty, 
    SUM(sr.Quantity) as TotalReturnQty
FROM 
    SalesLog sl
    LEFT JOIN Breakages br ON sl.ProductCode = br.ProductCode
    LEFT JOIN SalesReturn sr ON sl.ProductCode = sr.ProductCode
GROUP BY 
    sl.pName

这将为您提供按产品名称分组的总数量。

正如AakashM正确指出的那样,使用内连接只返回有破损和返回的记录,所以我将它们更改为左连接。