当设置特定值时,是否只能按特定行分组?
即。我有下表:
USERNO | FIRSTNAME | NAME | CUSTOMER | YEAR
1 | Jon | Snow | 0 | 2014
2 | Williams | Spear | 1 | 2015
1 | John | Snow | 1 | 2015
3 | Sam | Wells | 0 | 2014
3 | Sam | Wells | 0 | 2013
当CUSTOMER
为1时,它应按USERNO
分组。所以我想要以下结果:
USERNO | FIRSTNAME | NAME | CUSTOMER | YEAR
1 | Jon | Snow | 1 | 2014
2 | Williams | Spear | 1 | 2015
3 | Sam | Wells | 0 | 2014
3 | Sam | Wells | 0 | 2013
这可能吗?
提前致谢!
答案 0 :(得分:1)
您可以使用UNION
获取此类结果:
SELECT *
FROM tablename
WHERE CUSTOMER != 1
UNION
SELECT *
FROM tablename
WHERE CUSTOMER = 1
GROUP BY USERNO;
或者你也可以使用CASE
,但是当条件不满足时你必须指定ELSE
部分来分组记录:
SELECT *
FROM tablename
GROUP BY CASE WHEN CUSTOMER = 1 THEN USERNO ELSE columnname END;
如果您希望将结果分组为GROUP_CONCAT
分隔列表,则可以使用COMMA
这样的结果:
SELECT
GROUP_CONCAT(DISTINCT CAST(USERNO) AS CHAR),
GROUP_CONCAT(DISTINCT CAST(FIRSTNAME) AS CHAR),
GROUP_CONCAT(DISTINCT CAST(NAME) AS CHAR),
CUSTOMER,
GROUP_CONCAT(DISTINCT CAST(YEAR) AS CHAR)
FROM tablename
GROUP BY CUSTOMER;