2013-03-07 69 views
0

如果下面的代碼冒犯任何人作爲專業人員,讓我事先道歉,現在的問題: 下面的一切完成後,它吐出了我究竟是什麼在尋找,如果該列有一個字符串,我得到1,如果不是零。我的意圖是添加第7列,添加這些列,以便我可以將它彙集到報告中的公式中,並將其與另一列進行比較。我確信有可能在查詢中做,我只是不知道如何。 Server是SQL 2008SQL查詢添加一列,即案例後的行總和

select CASE 
WHEN [1 First Name] = '' 
THEN 1 
ELSE 0 
    END as "First Name 1", 
    CASE 
WHEN [1 Last Name] = '' 
THEN 1 
ELSE 0 
    END as "Last Name 1", 
    CASE 
WHEN [2 First Name] = '' 
THEN 1 
ELSE 0 
    END as "First name 2", 
    CASE 
WHEN [2 Last Name] = '' 
THEN 1 
ELSE 0 
    END as "Last Name 2", 
    CASE 
WHEN [3 First Name] = '' 
THEN 1 
ELSE 0 
    END as "First Name 3", 
    CASE 
WHEN [3 Last Name] = '' 
THEN 1 
ELSE 0 
    END as "Last Name 3" 
    FROM 
    member 
+1

您希望每列有SUM嗎?或者只計算表中所有列+行的空字符串? – gbn 2013-03-07 14:02:01

+0

基本上我想計算一行,所以第7列中的總數將是0到6之間的數字,具體取決於有多少列有字符串。我試圖儘可能地解釋這一點,我對此非常不滿。 – Jason1891 2013-03-07 14:51:42

回答

3

這將總結你的1秒對所有的行和列

SELECT 
    X.*, 
    "First Name 1"+ 
     "Last Name 1"+ 
     "First name 2"+ 
     "Last Name 2"+ 
     "First Name 3"+ 
     "Last Name 3" AS TheSum 
FROM 
    (
    SELECT 
     CASE WHEN [1 First Name] = '' THEN 1 ELSE 0 END as "First Name 1", 
     CASE WHEN [1 Last Name] = '' THEN 1 ELSE 0 END as "Last Name 1", 
     CASE WHEN [2 First Name] = '' THEN 1 ELSE 0 END as "First name 2", 
     CASE WHEN [2 Last Name] = '' THEN 1 ELSE 0 END as "Last Name 2", 
     CASE WHEN [3 First Name] = '' THEN 1 ELSE 0 END as "First Name 3", 
     CASE WHEN [3 Last Name] = '' THEN 1 ELSE 0 END as "Last Name 3" 
    FROM 
     member 
    ) X 
+0

這最終給我總共有166000個,我在找的是這樣的:名字/姓氏/名字2 /姓名2 /名字3 /姓名3 /總數 - 1/1/0/0/0/0/2 – Jason1891 2013-03-07 14:46:15

+0

+1我認爲你編輯你的就像我發佈我的。 :) – Taryn 2013-03-07 15:09:44

+0

對不起,我沒有注意到你編輯過,gah希望我能做2個最好的答案。謝謝你們的幫助。 – Jason1891 2013-03-07 15:16:13

2

除非我失去了一些東西你可以把你的當前查詢的子查詢,然後添加一個列有總數:

select "First Name 1", 
    "Last Name 1", 
    "First name 2", 
    "Last Name 2", 
    "First Name 3", 
    "Last Name 3", 
    ("First Name 1" +"Last Name 1"+"First name 2"+"Last Name 2"+"First Name 3"+"Last Name 3") As total 
from 
(
    select CASE 
      WHEN [1 First Name] = '' THEN 1 ELSE 0 
     END as "First Name 1", 
     CASE 
      WHEN [1 Last Name] = '' THEN 1 ELSE 0 
     END as "Last Name 1", 
     CASE 
      WHEN [2 First Name] = '' THEN 1 ELSE 0 
     END as "First name 2", 
     CASE 
      WHEN [2 Last Name] = '' THEN 1 ELSE 0 
     END as "Last Name 2", 
     CASE 
      WHEN [3 First Name] = '' THEN 1 ELSE 0 
     END as "First Name 3", 
     CASE 
      WHEN [3 Last Name] = '' THEN 1 ELSE 0 
     END as "Last Name 3" 
    FROM member 
) m 
+0

明白了,爲什麼最後的「m」(道歉,如果這是一個超noob問題) – Jason1891 2013-03-07 15:11:34

+0

@ Jason1891這是子查詢的別名。 SQL Server在派生表和子查詢上需要一個別名。順便說一句,你應該接受gbn的答案,他編輯他的職位正確的版本,就像我張貼我的。 :) – Taryn 2013-03-07 15:12:55