2017-03-24 80 views
1

設置我的表像下面SQL單行結果從多個SQL

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 

如何實現S'

回答

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 
+1

謝謝Sreenu131 – Geeme

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 

希望它能幫助。 :)

+0

感謝達拉傑·沙瑪 – Geeme

+0

歡迎。 @Geeme –

1

如果值只有0和1,則使用可以簡單地使用SUM

select sum(a), sum(b), sum(c), sum(d) from #temp; 

如果可以有更多其他的價值,並希望只計算1,那麼可以使用在case使用sum

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; 
+0

非常感謝GurV – Geeme