Group By with Union导致错误

时间:2016-07-17 20:16:25

标签: sql sql-server tsql

我想合并两个查询的输出 -

send: function (file, callback) {                                           // 88
  if (! (file instanceof window.File) && ! (file instanceof window.Blob))   // 89
    throw new Error("Not a file");

输出 -

select top(10) hex_code from dbo.colors

查询 -

+----------+
| hex_code |
+----------+
| #2ecc71  |
| #3498db  |
| #9b59b6  |
| #f1c40f  |
| #e67e22  |
| #e74c3c  |
| #2980b9  |
| #2c3e50  |
| #27ae60  |
| #f39c12  |
+----------+

输出 -

SELECT top(10) [Product], count([Product]) as Count
  FROM [dbo].[TableA] group by [Product] order by count([Product]) desc

我尝试使用+---------+-------+ | Product | Count | +---------+-------+ | A | 105 | | B | 99 | | C | 87 | | D | 75 | | E | 56 | | F | 52 | | G | 37 | | I | 18 | | K | 16 | | L | 15 | +---------+-------+ 合并输出,但group by子句不允许我这样做。我不知道如何将它与GROUP BY和ORDER BY子句一起使用。

我试过了 -

UNION

但这会导致错误。合并这两列的任何其他方式?

编辑 - 预期输出

SELECT top(10) [Product], count([Product]) as Count
  FROM [dbo].[TableA] group by [Product] order by count([Product]) desc
UNION
    select top(10) hex_code from dbo.colors

根据ScaisEdge的回答,出局就像

+---------+-------+----------+
| Product | Count | Hex Code |
+---------+-------+----------+
| A       |   105 | #2ecc71  |
| B       |    99 | #3498db  |
| C       |    87 | #9b59b6  |
+---------+-------+----------+
for all 10 rows.

注意 - 两列都会获取前10条记录。两个表都没有关系。 (我认为没有加入)

2 个答案:

答案 0 :(得分:2)

您需要join两个表/查询。如果您没有要加入的列,并且您只想将每个产品与任意颜色相匹配,则可以加入row_number(),例如:

select p.Product, p.Count, c.hex_code
from (
    SELECT top(10) 
        [Product], count([Product]) as Count,
        row_number() over (order by count([Product])) [rn]
    FROM [dbo].[TableA] 
    group by [Product] 
) p
left join (
    select top(10) 
        hex_code, 
        row_number() over (order by hex_code) [rn]
    from dbo.colors
) on p.rn=c.rn
order by p.Count desc

答案 1 :(得分:0)

如果是武断的,你可以这样做..

    ;With cte
    as
    (
    SELECT top(10) [Product], count([Product]) as Count
      FROM [dbo].[TableA] group by [Product] order by count desc
    )
  ,cte1
   as(
       select top 10 hex_code from dbo.colors 
     )
    select * from cte c
    cross apply
    (select top 1 hex_code from cte1 order by newid()
    )b