2016-07-17 25 views
0

我想合併兩個查詢的輸出 -集團通過與聯盟造成錯誤

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 | 
+---------+-------+ 

我試過使用UNION合併輸出,但group by子句不讓我。我不知道如何將它與GROUP BY和ORDER BY子句一起使用。

我試過 -

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 

但是這會導致錯誤。任何其他方式來合併這兩列?

編輯 - 預期輸出

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

隨着ScaisEdge的答覆,從快到像

A 105 #27ae60 
A 105 #2980b9 

注 - 這兩列取前10名的記錄。兩個表都沒有關係。 (沒有加入,我想)

+0

當你做一個聯盟,你需要同樣的每個查詢中的列數。您的第一個返回2列,第二個返回1(SQL中的聯合只是表示堆疊結果) – Massanu

+0

當bot表不相關時,顯示產品A的十六進制代碼(#2ecc71)的邏輯是什麼? – TheGameiswar

+0

輸出是進一步傳遞給JS庫,期望第三列作爲顏色值。 –

回答

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 
+0

您的查詢僅指定一種顏色。如果將'top 1'改爲'top 10',我可以得到與ScaisEdge相同的輸出 –

+0

這就是我們假設在有限的一組值中隨機獲得的結果,您可以對bot查詢做一個rownumber,並將它們加入 – TheGameiswar

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