0
CREATE TABLE newsarticles
    (katernenID int, Buitenland int, Economie int, Sport int, Cultuur int, Wetenschap int, Media int, userID int);

INSERT INTO newsarticles
    (katernenID, Buitenland, Economie, Sport, Cultuur, Wetenschap, Media, userID)
VALUES
    (1, 24, 5, 52, 3, 2, 3, 1),
    (3, 2, 0, 0, 1, 51, 66, 5),
    (4, 50, 2, 67, 41, 1, 54, 6),
    (5, 30, 1, 79, 0, 0, 12, 7),
    (6, 9, 26, 0, 100, 11, 0, 8),
    (7, 2, 14, 8, 1, 33, 98, 9),
    (8, 0, 1, 0, 1, 0, 0, 10);



SELECT
  userID,GROUP_CONCAT(amt ORDER BY amt DESC) AS four_highest
FROM
(
  SELECT userID, @rownum := @rownum + 1 AS rank, NAME, amt FROM (
    SELECT userID, Buitenland AS amt, 'Buitenland' AS NAME UNION
    SELECT userID, Economie, 'Economie'  UNION
    SELECT userID, Sport, 'Sport' UNION
    SELECT userID, Cultuur, 'Cultuur'  UNION
    SELECT userID, Wetenschap, 'Wetenschap'  UNION
    SELECT userID, Media, 'Media' 
         FROM( SELECT katernenID, Buitenland, Economie, Sport, Cultuur, Wetenschap, Media, userID FROM newsarticles  ) temp

  ) amounts, (SELECT @rownum := 0) r
) top4
GROUP BY userid

我想让 UNION 像上面的查询一样,但是 Union 不起作用。UNION 立即需要 FROM 语句。喜欢:

    SELECT userID, Wetenschap, 'Wetenschap'  
                 FROM( SELECT katernenID, Buitenland, Economie, Sport, Cultuur, Wetenschap, Media, userID FROM newsarticles  ) temp
                 UNION
    SELECT userID, Media, 'Media' 
         FROM( SELECT katernenID, Buitenland, Economie, Sport, Cultuur, Wetenschap, Media, userID FROM newsarticles  ) temp

但是我不能重复 FROM 语句,子查询中有太多的计算。有没有办法做到这一点,或者我错过了什么?

或者

我想要一个带有 max(a_percentage,b_percentage,c_percentage),SecondMAX(a_percentage,b_percentage,c_percentage),ThirdMAX(a_percentage,b_percentage,c_percentage) 的新列

    SELECT id,a,b,c,a_percentage,b_percentage,c_percentage
    -- -------------------------max percentage
    GREATEST(axis_per, hdfc_per,icici_per,citi_per ) AS max_per,
    FROM (
      SELECT id,a,b,c,
      IFNULL(a*100/a+b+c+d,0) AS a_percentage,
      IFNULL(b*100/a+b+c+d,0) AS b_percentage,
      IFNULL(c*100/a+b+c+d,0) AS c_percentage
      FROM test
        WHERE TIME > '2012-01-01'
        GROUP BY id
      ) A
4

1 回答 1

0

如果我对您的理解正确,您应该能够只使用 中的表名FROM,并为每行上的列加上别名,例如:

SELECT
  userID,GROUP_CONCAT(amt ORDER BY amt DESC) AS four_highest
FROM
(
  SELECT userID, @rownum := @rownum + 1 AS rank, NAME, amt FROM (
    SELECT userID, Buitenland AS amt, 'Buitenland' AS NAME FROM newsarticles NAME UNION
    SELECT userID, Economie, 'Economie'  FROM newsarticles UNION
    SELECT userID, Sport, 'Sport'  FROM newsarticles UNION
    SELECT userID, Cultuur, 'Cultuur'  FROM newsarticles UNION
    SELECT userID, Wetenschap, 'Wetenschap'  FROM newsarticles UNION
    SELECT userID, Media, 'Media' FROM newsarticles
) amounts, (SELECT @rownum := 0) r
) top4
GROUP BY userid
于 2012-11-09T15:28:07.590 回答