我有一张名字和区域的桌子。 我想运行一个返回该表的查询,并添加一个'Special_COUNT' 计数在最前面的Concat(Distinct(Name,Area))上返回1;否则返回0 例如:
Name | Area | Special_COUNT |
ABCD | US | 1 |
ABCD | US | 0 |*Same Name/Region no value
ABCD | Asia | 1 |*New Region
ABCDX | Asia | 1 |*New Name
如何将上述'Special_COUNT'列添加到我的查询结果中?
答案 0 :(得分:1)
MySQL没有任何排名功能 - 您需要read this article来设置LEAD功能的变量,以便正确地对输出进行编号。
使用:
SELECT x.name,
x.area,
x.special_count
FROM (SELECT t.name,
t.area,
CASE WHEN @name = t.name AND @area = t.area THEN 0 ELSE 1 END AS special_count,
@name := t.name,
@area := t.area
FROM TABLE t,
(SELECT @area := NULL, @name := NULL) r) x
在4.1上测试 - 结果匹配,感谢您提供测试数据。
答案 1 :(得分:0)
谢谢!
你的代码看起来很简单,唉我无法将其用于更大的查询(不提供示例查询的道歉,以便你可以告诉我这是如何工作的,下面我已经为你做了希望你可以通过例子解释)
因此,在下面的原始查询中,我将如何修改它以合并您的数据,目标是在每个location.Area上的allanimalnames.AnimalName上获取'special_count'。
我看到隧道尽头的灯光......
SELECT
CASE allanimalnames.animalID
WHEN allanimalnames.animalID = 1 THEN "Dangerous!"
WHEN allanimalnames.animalID <> 1 THEN "Cuddly"
END AS 'Animal Danger Levell,
allanimalsizes.SizeInFeet AS 'Length of the Animal',
allanimaltypes.AnimalTypeName AS 'Carnivor or Herbavore?',
location.Area AS 'Region this Animal is found in',
allanimalnames.AnimalName AS 'Name of this animal,
MAX(report.reportdate) AS 'Last Reported'
FROM
allanimalnames
INNER JOIN allanimaltypes ON allanimaltypes.atypeid = allanimalnames.atypeid
INNER JOIN allanimalsizes ON allanimalsizes.sizeid = allanimalnames.sizeid
INNER JOIN location ON location.locid = allanimalnames.locid
INNER JOIN report ON report.reportid = allanimalnames.reportid
WHERE
report.reportdate
BETWEEN '2008-01-01' AND '2009-01-01'
GROUP BY
allanimalsizes.SizeInFeet
allanimaltypes.AnimalTypeName
location.Area
allanimalnames.AnimalName
report.reportdate