计算连接表返回的不同数量的项目

时间:2015-12-19 19:32:07

标签: sql sqlite join

我有3张桌子,User, Payment, Type Of Payment 像:

CREATE TABLE User (
  `userID` INTEGER PRIMARY KEY AUTOINCREMENT, 
  `userName` varchar(4)
  );
INSERT INTO User values    
    (1, 'Tom'),
    (2, 'Kate'),
    (3, 'Karla');

CREATE TABLE typePayment ( 
  typeID    INTEGER PRIMARY KEY AUTOINCREMENT, 
  namePayment      VARCHAR(6) NOT NULL
);
INSERT INTO typePayment values
(1,'Cash'),
(2,'Check'),
(3,'Both');

CREATE TABLE Payment (
  `paymentID` INTEGER PRIMARY KEY AUTOINCREMENT,
  `idUser` int, 
  `idTypePayment` int, 
  `info` varchar(14)  
  );

INSERT INTO Payment VALUES
    (1, 1, 1, 'ball'),
    (2, 1, 1, 'book'),
    (3, 1, 2, 'book'),
    (4, 2, 1, 'book');

当加入表格以咨询我所得到的付款时

userID  userName    namePayment     info
1       Tom         Cash            ball
1       Tom         Cash            book
1       Tom         Check           book
2       Kate        Cash            book

通过以下查询

SELECT u.userID ,u.userName, te.namePayment , e.info
FROM User u
  INNER JOIN Payment e 
     ON u.userID = e.idUser     
  INNER JOIN typePayment te 
     ON e.idTypePayment = te.typeID
 order by u.userID;

但是,我想计算每个人的总付款类型数量,如:

userID  userName    namePayment     info    noCash  noCheck  noBoth
1       Tom         Cash            ball        2         1       0
1       Tom         Cash            book        2         1       0
1       Tom         Check           book        2         1       0
2       Kate        Cash            book        1         0       0

怎么做? (请查看fiddle,我正在使用SQLite)

1 个答案:

答案 0 :(得分:3)

为什么要为用户提供多行?此外,noBoth没有意义。

此查询获取每位用户的不同付款类型:

SELECT u.userID, u.userName,
       SUM(CASE WHEN te.namePayment = 'Cash' THEN 1 ELSE 0 END) as NumCash,           
       SUM(CASE WHEN te.namePayment = 'Check' THEN 1 ELSE 0 END) as NumCheck,
       SUM(CASE WHEN te.namePayment IN ('Cash', 'Check' ) THEN 1 ELSE 0 END) as NumBoth
FROM User u INNER JOIN
     Payment e 
     ON u.userID = e.idUser INNER JOIN
     typePayment te 
     ON e.idTypePayment = te.typeID
GROUP BY u.userID;
ORDER BY u.userID;

如果您真的喜欢,可以将其加入到更详细的信息中,以便为每次付款添加列。