查一次表可以实现吗
A:
---------------------------
id name sex marry
1 a 0 1
2 b 0 0
3 c 1 1
4 d 0 0
5 e 1 1
6 f 0 0
7 g 0 1
8 h 0 0
能不能一次查表得出
-----------------
总数:8
sex为0:6
sex为1:2
marry为0:4
marry为1:4
-----------------
------解决方案-------------------- try
Select
Count(*) As 总数,
SUM(Case sex When 0 Then 1 Else 0 End) As [sex为0],
SUM(Case sex When 1 Then 1 Else 0 End) As [sex为1],
SUM(Case marry When 0 Then 1 Else 0 End) As [marry为0],
SUM(Case marry When 1 Then 1 Else 0 End) As [marry为1]
From
A
------解决方案--------------------LZ能解释下结果是怎样出来的吗?看不懂
------解决方案--------------------sex为0:6
sex为1:2
marry为0:4
marry为1:4
..................
我还以为你说
sex为 0:6
sex为 1:2
marry为 0:4
marry为 1:4
看了鱼的才知道~~
------解决方案--------------------SELECT
总数 = count(*),
sex0 = sum(case sex when 0 then 1 else 0 end),
sex1 = sum(case sex when 1 then 1 else 0 end),
marry0 = sum(case marry when 0 then 1 else 0 end),
marry1 = sum(case marry when 1 then 1 else 0 end)
FROM table
------解决方案--------------------Create Table A
(id Int,
name Varchar(10),
sex Bit,
marry Bit)
Insert A Select 1, 'a ', 0, 1
Union All Select 2, 'b ', 0, 0
Union All Select 3, 'c ', 1, 1
Union All Select 4, 'd ', 0, 0
Union All Select 5, 'e ', 1, 1
Union All Select 6, 'f ', 0, 0
Union All Select 7, 'g ', 0, 1
Union All Select 8, 'h ', 0, 0
GO
Select
Count(id) As 总数,
SUM(Case sex When 0 Then 1 Else 0 End) As [sex为0],
SUM(Case sex When 1 Then 1 Else 0 End) As [sex为1],
SUM(Case marry When 0 Then 1 Else 0 End) As [marry为0],
SUM(Case marry When 1 Then 1 Else 0 End) As [marry为1]
From
A
GO
Drop Table A
--REsult
/*
总数 sex为0 sex为1 marry为0 marry为1
8 6 2 4 4
*/