2015-02-24 144 views
1

我試圖從同一個表中選擇多個值。我需要從工作臺表的posts table和station_title中選擇列rfid和process_status的計數值。使用Android中的SQLite數據庫表對同一個表中的兩個不同的列值進行計數

這裏有兩個表:

帖子表:

 
Id ownerId rfid stationId  stationType process_status 
1  107  rfid1 raj1222681607 like    pending 
2  107  rfid1 raj1222681607 like    pending 
3  107  rfid1 raj1125396157 like    pending 
4  107  rfid1 raj1222681607 like    
5  107  rfid2 raj1222681607 like    pending 
6  107  rfid3 raj1222681607 like    

站表:

 
Id title ownerId stationId  stationLike stationPic 
1 Check-in one   107    raj1125396157 1    0 
2 nfc station 01  107    raj1222681607  1    0 

從這兩個表我想數據

 
Total RFIDs : 5 
Total Pending : 3 
Station Title : nfc station 01 

where子句的條件是:OWNERID = 107和的stationID =「raj1222681607」和process_status =「掛起」

到目前爲止我可以實現RFID的總,站標題值;但我無法獲得計算進程狀態的總待處理值。

我的查詢片段:

SELECT 
     COUNT(p.rfid) as TotalTap, 
     COUNT(p.process_status) as TotalPending, 
     s.title 
    FROM posts p 
    inner join 
    stations s 
    on p.stationId = s.stationId 
    WHERE 
    p.ownerId = 107 AND p.stationId = 'raj1222681607' 
    AND p.process_status = 'pending'; 

但是,這是給了錯誤的輸出: RFID的總數:3(這是錯誤的!) 總待定:3 電臺標題:NFC臺01

回答

0

爲了計算有多少行符合條件,使用SUM在布爾表達式:

SELECT COUNT(*) AS TotalTap, 
     SUM(process_status = 'pending') AS TotalPending 
FROM Posts 
WHERE ownerId = 107 
    AND stationId = 'raj1222681607'; 

它確實嘗試計算同一查詢中的第三個值沒有任何意義;只使用一個單獨的,更簡單的查詢:

SELECT title 
FROM Stations 
WHERE stationId = 'raj1222681607'; 

Android有此一helper function

String title = DatabaseUtils.stringForQuery(db, 
        "SELECT title FROM Stations WHERE stationId = ?", 
        new String[]{ "raj1222681607" }); 
+0

嗨CL,感謝您的指正。進程狀態值是字符串格式。所以總和會是不錯的選擇?我需要從一個數據庫函數調用中獲取所有這些信息。所以我需要也得到標題值。 – 2015-02-24 15:05:16

+0

表達式'process_status ='pending''的值可以是'0'或'1'。 – 2015-02-24 15:06:03

+0

我的查詢是:SELECT COUNT(p.rfid)as TotalTap, (SELECT COUNT(p.process_status)FROM posts p WHERE p.ownerId =?AND p.stationId =?AND p.process_status =?)as TotalPending, s.title 來自帖子p 內部聯接 站上p.stationId小號 = s.stationId WHERE p.ownerId = 107和p.stationId = 'raj1222681607' 和p.process_status = '掛起';但我無法從光標調用中獲取這些值。 – 2015-02-24 15:07:33

相關問題