mysql query: SELECT DISTINCT column1, GROUP BY column2

后端 未结 5 614
后悔当初
后悔当初 2020-12-30 02:02

Right now I have the following query:

SELECT name, COUNT(name), time, price, ip, SUM(price) 
  FROM tablename 
 WHERE time >= $yesterday 
   AND time <         


        
相关标签:
5条回答
  • 2020-12-30 02:37

    Replacing FROM tablename with FROM (SELECT DISTINCT * FROM tablename) should give you the result you want (ignoring duplicated rows) for example:

    SELECT name, COUNT(*)
    FROM (SELECT DISTINCT * FROM Table1) AS T1
    GROUP BY name
    

    Result for your test data:

    dave 2
    mark 2
    
    0 讨论(0)
  • 2020-12-30 02:40

    Somehow your requirement sounds a bit contradictory ..

    group by name (which is basically a distinct on name plus readiness to aggregate) and then a distinct on IP

    What do you think should happen if two people (names) worked from the same IP within the time period specified?


    Did you try this?

    SELECT name, COUNT(name), time, price, ip, SUM(price) 
      FROM tablename 
     WHERE time >= $yesterday AND time <$today 
    GROUP BY name,ip
    
    0 讨论(0)
  • 2020-12-30 02:43

    Try the following:

    SELECT DISTINCT(ip), name, COUNT(name) nameCnt, 
    time, price, SUM(price) priceSum
    FROM tablename 
    WHERE time >= $yesterday AND time <$today 
    GROUP BY ip, name
    
    0 讨论(0)
  • 2020-12-30 02:44

    you can use COUNT(DISTINCT ip), this will only count distinct values

    0 讨论(0)
  • 2020-12-30 02:44

    You can just add the DISTINCT(ip), but it has to come at the start of the query. Be sure to escape PHP variables that go into the SQL string.

    SELECT DISTINCT(ip), name, COUNT(name) nameCnt, 
    time, price, SUM(price) priceSum
    FROM tablename 
    WHERE time >= $yesterday AND time <$today 
    GROUP BY ip, name
    
    0 讨论(0)
提交回复
热议问题