我真的不明白你想要什么...
create table #tshirt (
tshirt_id int,
tshirt_name varchar(10),
tshirt_color varchar(15),
tshirt_size varchar(2)
)
insert into #tshirt values (1, 'TShirt1', 'RedCrew', 'L')
insert into #tshirt values (2, 'TShirt1', 'RedCrew', 'L')
insert into #tshirt values (3, 'TShirt1', 'BlueSlim', 'M')
insert into #tshirt values (4, 'TShirt1', 'BlueSlim', 'M')
insert into #tshirt values (5, 'TShirt1', 'BlueSlim', 'M')
insert into #tshirt values (6, 'TShirt1', 'BlueSlim', 'M')
insert into #tshirt values (7, 'TShirt2', 'GreyV', 'S')
insert into #tshirt values (8, 'TShirt2', 'BlueSlim', 'XL')
SELECT tshirt_name, tshirt_color, tshirt_size, count(*) as ct
FROM #tshirt
GROUP BY tshirt_name, tshirt_color, tshirt_size
ORDER BY tshirt_name, tshirt_color, tshirt_size
--tshirt_name tshirt_color tshirt_size ct
--TShirt1 BlueSlim M 4
--TShirt1 RedCrew L 2
--TShirt2 BlueSlim XL 1
--TShirt2 GreyV S 1
SELECT tshirt_name, count(*) as ct
FROM #tshirt
GROUP BY tshirt_name
--tshirt_name ct
--TShirt1 6
--TShirt2 2
根据我的数据和架构:
SELECT tshirt_color, tshirt_size, count(*) as ct
FROM #tshirt
GROUP BY tshirt_color, tshirt_size
ORDER BY tshirt_color, tshirt_size
--tshirt_color tshirt_size ct
--BlueSlim M 4
--BlueSlim XL 1
--GreyV S 1
--RedCrew L 2
我认真建议更改您的表架构
create table #tshirt (
TShirt_id int,
TShirt1 varchar(100),
TShirt1Size varchar(100),
TShirt2 varchar(100),
TShirt2Size varchar(100)
);
insert into #tshirt values (1, 'RedCrew', 'XL', 'BlueSlim', 'M');
insert into #tshirt values (2, 'BlueSlim', 'L', 'RedCrew', 'L');
insert into #tshirt values (3, 'GreyV', 'L', 'BlueSlim', 'M');
insert into #tshirt values (4, 'BlueSlim', 'M', '', '');
insert into #tshirt values (5, '', '', 'GreyV', 'L');
insert into #tshirt values (6, 'BlueSlim', 'S', 'BlueSlim', 'L');
select tshirt_desc, tshirt_size, COUNT(*) as ct
from ( select
TShirt1 as tshirt_desc,
TShirt1Size as tshirt_size
from #tshirt
union all
select
TShirt2 as tshirt_desc,
TShirt2Size as tshirt_size
from #tshirt ) as tshirt
group by tshirt_desc, tshirt_size
order by tshirt_desc, tshirt_size
--tshirt_desc tshirt_size ct
-- 2
--BlueSlim L 2
--BlueSlim M 3
--BlueSlim S 1
--GreyV L 2
--RedCrew L 1
--RedCrew XL 1
试试这个..(我不得不使用在线格式化程序 b/c 我的很草率)
SELECT tshirt1 AS TShirt,
tshirt1size AS TShirtSize,
(SELECT ct
FROM (SELECT tshirt,
tshirtsize,
Count(*) AS ct
FROM (SELECT tshirt1 AS TShirt,
tshirt1size AS TShirtSize
FROM #tshirt
UNION ALL
SELECT tshirt2 AS TShirt,
tshirt2size AS TShirtSize
FROM #tshirt) AS tshirt
GROUP BY tshirt,
tshirtsize) AS inner_t
WHERE inner_t.tshirt = outer_t.tshirt1
AND inner_t.tshirtsize = outer_t.tshirt1size) AS ct
FROM #tshirt AS outer_t
http://sqlfiddle.com/#!3/ec024/8/0
outer_t
如果需要,您可以轻松删除别名...