Mysql Group BY用if语句

时间:2011-11-16 22:15:02

标签: mysql if-statement group-by

我不确定这是否可以在没有嵌套选择的单个select语句中执行。

我正在对结果进行分组,我想知道如果整个分组中的字段包含条件,则显示是。使用它,它将从组中取第一行并检查条件而不是组中的所有行

if(field = 'condition','yes','no') as field_found

3 个答案:

答案 0 :(得分:1)

示例表:id,得分

SELECT t1.id, (
  SELECT IF("10" IN (
    SELECT score FROM table t2 WHERE t1.id = t2.id
  ),'yes','no')) 
FROM table t1
GROUP BY t1.id

有效吗?

答案 1 :(得分:0)

if(GROUP_CONCAT(field) LIKE '%condition%','yes','no')

SELECT first_name,last_name, CONCAT(physical_address," ",physical_address2," ",city, " ",zip) as address, MONTHNAME(install_date) as billing_month, IFNULL(status.quantity,0) as total_measures_instalclient2d,IFNULL(client1_measures,"") as client1_measures,IFNULL(client2_measures,"") as client2_measures,IFNULL(client1_quantity,0) as client1_quantity,IFNULL(client2_quantity,0) as client2_quantity,if(GROUP_CONCAT(measure_list.measure_type) LIKE '%Outreach/ Assessment%','yes','no') as outreach_invoiced,GROUP_CONCAT(IF(client='Client1',CONCAT(percent*100,"%-",measure_list.measure_type),NULL)) as client1_percent,GROUP_CONCAT(IF(client='Client2',CONCAT(percent*100,"%-",measure_list.measure_type),NULL)) as client2_percent,work_order.notes FROM customers
INNER JOIN measure on measure.customer_id = customers.customer_id
INNER JOIN measure_list on measure_list.measure_list_id = measure.measure_list_id
INNER JOIN work_order on work_order.work_order_id = measure.work_order_id
INNER JOIN billing on billing.workmanship = work_order.workmanship AND billing.measure_type = measure_list.measure_type
LEFT JOIN (
SELECT customers.customer_id,SUM(quantity) as quantity,GROUP_CONCAT(IF(client='Client1',measure_description,NULL)) as client1_measures,GROUP_CONCAT(IF(client='client2',measure_description,NULL)) as client2_measures,SUM(IF(client='client1',quantity,0)) as client1_quantity,SUM(IF(client='client2',quantity,0)) as client2_quantity FROM customers
INNER JOIN measure on measure.customer_id = customers.customer_id
INNER JOIN measure_list on measure_list.measure_list_id = measure.measure_list_id
INNER JOIN work_order on work_order.work_order_id = measure.work_order_id
INNER JOIN billing on billing.workmanship = work_order.workmanship AND billing.measure_type = measure_list.measure_type
WHERE measure_list.measure_type NOT IN ('measure1','measure2')
GROUP BY customers.customer_id
) as status on status.customer_id = customers.customer_id
WHERE measure_list.measure_type IN ('measure1','measure2')
GROUP BY customers.customer_id

答案 2 :(得分:0)

由于您已经在进行分组,因此您应该能够将MAX()添加为具有您期望条件的列,并将其添加到组中......例如

select 
      MAX( if( field LIKE '%condition%','1', '2' )) as ExtraOrderBy,
      First_Name,
      Last_Name,
      ... rest of query ...
   group by
      customers.Customer_ID
   order by
      1

在这种情况下,order by是SQL列表中的序数列,而不是显式重新输入MAX(IF())条件......所以,如果条件为真,则用“1”标记,否则“ 2“将所有符合条件的人浮动到列表顶部...然后,您可以通过其他内容(如姓氏,名字或您查询的其他字段)进行子订单。