现有表store ,表中数据如下图所示:
如何通过sql语句 查出下面这种结果:
字段:id cname(药店) product_name(药品名) specification1(药品规格1) specification2(药品规格2)
请问应该如何写,求大神赐教,感激不尽……
CREATE TABLE [dbo].[store](
[id] [int] NOT NULL,
[cname] [varchar](50) NULL,
[product_name] [varchar](50) NULL,
[specification1] [varchar](50) NULL
) ON [PRIMARY]
INSERT [dbo].[store] ([id], [cname], [product_name], [specification1]) VALUES (1, N'a药店', N'阿莫西林', N'6片装')
INSERT [dbo].[store] ([id], [cname], [product_name], [specification1]) VALUES (2, N'a药店', N'阿莫西林', N'16片装')
INSERT [dbo].[store] ([id], [cname], [product_name], [specification1]) VALUES (3, N'b药店', N'阿莫西林', N'6片装')
试试这个语句可以吗
select s.id,s.cname,s.product_name,s.specification1,s.specifiaction2 from store s,store t where s.canme=t.cname(+) and s.specifiaction1 =t.specification1(+);
你这个药品规格最多只可能两种吗?还是说不确定可能很多种?这个是把竖表变成横表,如果确认药品规格只有两种的话可以这么写,考虑到规格不只是
6片装或者24片装,
select a.cname,a.product_name,a.specification1,b.specification1 specification2 from (select cname,product_name,min(specification1) from store group by cname,prodcut_name)a,
(select cname,product_name,max(specification1) from store group by cname,product_name) b where a.cname=b.cname and a.product_name=b.product_name;
你这种设计不是很科学
select cname,product_name,
sum(case when specification1='6片装' then specification1 end) as specification1,
sum(case when specification1='16片装' then specification1 end) as specification2
from store
group by cname,product_name;
哈哈,Oracle中可以行列转换。