使用android中的SQLite Database表计算同一个表中的两个不同列值

时间:2015-02-24 11:24:14

标签: sqlite android-sqlite

我正在尝试从同一个表中选择多个值。我需要从posts表和station_title中选择列rfid和process_status的计数值。

以下是两个表格:

帖子表:

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 ='待定'

到目前为止,我可以实现总rfids,站标题值;但我无法得到计算过程状态的总待定值。

我的查询摘要:

  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 station 01

1 个答案:

答案 0 :(得分: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" });