我有如下表格
create table #temp
(
a int null,
b int null,
c int null,
d int null
)
insert into #temp values (0,0,0,0)
insert into #temp values (0,1,0,0)
insert into #temp values (0,0,0,1)
insert into #temp values (0,1,0,0)
我试过
select * from(
(select count(*) a from #temp where a=1 group by a) dt1 cross join
(select count(*) b from #temp where b=1 group by b) dt2 cross join
(select count(*) c from #temp where c=1 group by c) dt3 cross join
(select count(*) d from #temp where d=1 group by d) dt4
)
但没有获得任何输出
我希望得到如下所示的输出
a b c d
0 2 0 1
如何实现这一目标?
答案 0 :(得分:3)
试试这个:
DECLARE @temp TABLE( a int , b int , c int , d int )
insert into @temp values (0,0,0,0),(0,1,0,0),
(0,0,0,1),(0,1,0,0)
SELECT SUM(a) a,SUM(b) b,SUM(c) c,SUM(d) d FROM @temp
希望它有所帮助。 :)
答案 1 :(得分:2)
IF OBJECT_ID('tempdb..#TEMP') IS NOT NULL
DRop Table #TEMP
CREATE TABLE #TEMP
(
A INT NULL,
B INT NULL,
C INT NULL,
D INT NULL
)
INSERT INTO #TEMP VALUES (0,0,0,0)
INSERT INTO #TEMP VALUES (0,1,0,0)
INSERT INTO #TEMP VALUES (0,0,0,1)
INSERT INTO #TEMP VALUES (0,1,0,0)
SELECT * FROM #TEMP
SELECT SUM(A)A,SUM(B)B,SUM(C)C,SUM(D)D FROM #TEMP
答案 2 :(得分:1)
如果值仅为0和1,那么使用只需使用SUM
:
select sum(a), sum(b), sum(c), sum(d) from #temp;
如果可以有更多其他值,并且您只想计算1,则可以使用sum
上的case
:
select sum(case when a = 1 then 1 else 0 end),
sum(case when b = 1 then 1 else 0 end),
sum(case when c = 1 then 1 else 0 end),
sum(case when d = 1 then 1 else 0 end)
from #temp;