我在 sql-server 2005 express DB 中有 2 个表
1. 商品尺寸表
CREATE TABLE [dbo].[ItemSize](
[ID] [int] IDENTITY(1,1) NOT NULL,
[iSize] [int] NULL
) ON [PRIMARY]
2.销售日志表
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) NULL,
[pSize] [int] NULL,
[BillDate] [nchar](10) NULL,
CONSTRAINT [PK_SalesLog] PRIMARY KEY CLUSTERED
(
[SalesID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
ItemSize 表包含不同尺寸的饮料喜欢
100毫升
200
毫升 300毫升
400毫升
500毫升
我想要 ItemSize 表列 (iSize) 数据作为列
ItemName 100ml 200ml 300ml 400ml 500ml
Drink A 10 20 5 4 30
Drink B 20 10 15 35 40
并且数据将根据尺寸和产品名称从销售表中排列,如上所示。
我有类似的查询,但它不是动态的。我的意思是,如果我向 ItemSize 表添加新大小,那么它将无法报告。所以我需要解决方案。
目前我正在使用此查询根据商品大小获取销售额
select i.gName,
isnull((select
sum(Quantity)from saleslog where BillDate='01-06-2010' and pSize=0 and
pGroup=i.gCode),0) as '0ml',
isnull((select
sum(Quantity)from saleslog where BillDate='01-06-2010' and pSize=180 and
pGroup=i.gCode),0) as '180ml',
isnull((select
sum(Quantity)from saleslog where BillDate='01-06-2010' and pSize=375 and
pGroup=i.gCode),0) as '375ml',
isnull((select
sum(Quantity)from saleslog where BillDate='01-06-2010' and pSize=500 and
pGroup=i.gCode),0) as '500ml',
isnull((select
sum(Quantity)from saleslog where BillDate='01-06-2010' and pSize=650 and
pGroup=i.gCode),0) as '650ml',
isnull((select
sum(Quantity)from saleslog where BillDate='01-06-2010' and pSize=750 and
pGroup=i.gCode),0) as '750ml',
isnull((select
sum(Quantity)from saleslog where BillDate='01-06-2010' and pSize=1000 and
pGroup=i.gCode),0) as '1000ml',
isnull((select
sum(Quantity)from saleslog where BillDate='01-06-2010' and
pSize=2000 and pGroup=i.gCode),0) as '2000ml'
from saleslog as s
inner join ItemGroup as i on s.pGroup=i.gCode
where BillDate='01-06-2010'
group by i.gCode, i.gName
答案1
你检查过枢功能?您没有提到您使用的是哪个 SQL 版本,但它在 2008 年可用,并且基本上可以满足您的要求。
此外,您的代码似乎效率极低。您在选择内执行选择,以取回您已经可以访问的数据。也许我很难识别您的数据集,但在您当前的情况下,似乎需要一个案例陈述,而不是大量的选择。我相信以下方法有效:
select
i.gName,
case i.pSize when 0 then sum(Quantity) else 0 end as [0ml],
case i.pSize when 180 then sum(Quantity) else 0 end as [180ml],
case i.pSize when 375 then sum(Quantity) else 0 end as [375ml],
{ rest of case samples }
from
saleslog as s
inner join ItemGroup as i on s.pGroup = i.gGroup
where
s.BillDate = '01-06-2010'
group by
i.gName
我对你的问题也有点困惑。你提到你有两个表,一个有 id 和 iSize,但我没有看到 iSize,所以我假设是 pSize(?)。此外,你的销售表与查询不匹配,即销售表中没有数量金额,你的创建提到了 [sales],但你的实际查询使用的是 [salesdata]。
也许更能说明一些?