使用php mysql使用Subquery获取每条记录的计数

时间:2014-02-26 10:31:27

标签: php mysql

我的Db设计是:

 Tbl_id       booked_by   date
    1          W          2014-02-01
    2          P          2014-02-01
    3          P          2014-02-01
    4          P          2014-02-01
    5          W          2014-02-04
    6          W          2014-02-04
    7          P          2014-02-04

我想显示W,P的计数给定日期和按日期分组并使用php mysql ...

喜欢

我需要这样的输出:

Tbl_id  W    P   date
   1    1    3  2014-02-01
   2    2    1  2014-02-04

我需要Mysql Query来获取上面给出的输出..

4 个答案:

答案 0 :(得分:1)

您需要SUM()函数,而不是COUNT()。

SELECT
SUM(No_people),
SUM(Breakfast),
SUM(Lunch),
`date`
FROM yourTable
GROUP BY `date`

我没有包含Tbl_id,因为您选择的每个列必须与聚合函数一起使用或包含在group by子句中。否则,它未确定选择了哪一行组。无论如何选择它只适用于MySQL,但它不符合SQL标准。如果您想要某种行号而不是Ravinder的方法,或者在应用程序级别创建一个(这当然更容易)。

更新:

SELECT
SUM(booked_by = 'W') AS W,
SUM(booked_by = 'P') AS P,
`date`
FROM yourTable
GROUP BY `date`

您仍然需要SUM()函数。 booked_by = 'whatever'的计算结果为true(1)或false(0)。

答案 1 :(得分:1)

您需要使用SUM聚合函数进行求和,并使用Tbl_id的临时行号。

select
 @rwnm:=@rwnm+1 as Tbl_id,
 sum(No_people) as No_people,
 sum(Breakfast) as Breakfast,
 sum(Lunch) as Lunch,
 date 
from my_table, ( select @rwnm := 0 ) rownums
group by date

答案 2 :(得分:0)

如果你想只是在下面没有slno的结果查询将正常工作

SELECT 
SUM(No_People) as No_People, 
SUM(Breakfast) as Breakfast,
Sum(Lunch) as Lunch,
`date` as date
FROM table_Name
GROUP BY `date`

输出:

No_people  Breakfast Lunch   date
    84       112      160    2014-02-11
    116      96       118    2014-02-04

但如果你也想要序列号。要显示,然后查询将工作

SELECT 
@slno := @slno + 1 as slno
SUM(No_People) as No_People, 
SUM(Breakfast) as Breakfast,
Sum(Lunch) as Lunch,
`date` as date
FROM table_Name, (select @slno := 0 ) sln
GROUP BY `date`

输出:

slno  No_people  Breakfast Lunch   date
   1          84    112      160    2014-02-11
   2         116    96       118    2014-02-04

答案 3 :(得分:0)

考虑以下数据集......

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id       INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,booked_by   CHAR(1) NOT NULL
,date DATE NOT NULL
);

INSERT INTO my_table VALUES
(1,'W','2014-02-01'),
(2,'P','2014-02-01'),
(3,'P','2014-02-01'),
(4,'P','2014-02-01'),
(5,'W','2014-02-04'),
(6,'W','2014-02-04'),
(7,'P','2014-02-04');

这是一个数据透视查询...

SELECT date
     , COUNT(CASE WHEN booked_by = 'W' THEN 'foo' END) W
     , COUNT(CASE WHEN booked_by = 'P' THEN 'foo' END) P 
  FROM my_table 
 GROUP 
    BY date;
+------------+---+---+
| date       | W | P |
+------------+---+---+
| 2014-02-01 | 1 | 3 |
| 2014-02-04 | 2 | 1 |
+------------+---+---+

在我看来,一个更好的想法(更灵活,更具可扩展性)只是返回一个GROUPED(因此,有序)结果集并处理表示层中的其余部分(例如一个简单的PHP循环)。

SELECT date,booked_by,COUNT(*) ttl FROM my_table GROUP BY date,booked_by;
+------------+-----------+-----+
| date       | booked_by | ttl |
+------------+-----------+-----+
| 2014-02-01 | P         |   3 |
| 2014-02-01 | W         |   1 |
| 2014-02-04 | P         |   1 |
| 2014-02-04 | W         |   2 |
+------------+-----------+-----+