2016-01-22 67 views
2
一行

,使一行的結果顯示,而不是多行:SQL查詢組合成我有一些困難,結合以下查詢

SELECT value FROM dbo.parameter WHERE name='xxxxx.name' 
SELECT dbo.contest.name AS Event_Name 
FROM contest 
INNER JOIN open_box on open_box.contest_id = contest.id 
GROUP BY dbo.contest.name 

SELECT COUNT(*) FROM open_option AS total_people 

SELECT SUM(scanned) AS TotalScanned,SUM(number) AS Totalnumber 
FROM dbo.open_box 
GROUP BY contest_id 

SELECT COUNT(*) FROM open AS reff 
WHERE refer = 'True' 

我想從顯示的字段數據在每一列中與下圖中顯示的相似。任何幫助表示讚賞!

enter image description here

+1

這就像轉置的東西。你想要它多列還是隻有一個字段(串聯)? – DukeOfHazard

+1

歡迎您通過展示您的預期結果模型來獲得更快的答案... – downwitch

+0

對不起 - 應該顯示我想要的。我想多列,但所有的數據在一行 - 我需要能夠從一張表提取到一張新表 –

回答

2

Tab的解決方案很好,我只是想展示一個替代方法。下面的語句使用subqueries來獲取信息的一行:

SELECT 
    [xxxx.name]=(SELECT value FROM dbo.parameter WHERE name='xxxxx.name'), 
    [Event Name]=(SELECT dbo.contest.name 
     FROM contest 
     INNER JOIN open_box on open_box.contest_id = contest.id 
     GROUP BY dbo.contest.name), 
    [Total People]=(SELECT COUNT(*) FROM open_option), 
    [Total Scanned]=(SELECT SUM(scanned) 
     FROM dbo.open_box 
     GROUP BY contest_id), 
    [Total Number]=(SELECT SUM(number) 
     FROM dbo.open_box 
     GROUP BY contest_id), 
    Ref=(SELECT COUNT(*) FROM open WHERE refer = 'True'); 

這需要Total ScannedTotal Number必須另外查詢。


更新:如果你那麼想INSERT是到另一個表主要有兩種方法可以做到這一點。

  1. 直接從SELECT語句來創建該表:

SELECT 
    -- the fields from the first query 
INTO 
    [database_name].[schema_name].[new_table_name]; -- creates table new_table_name 

  • 插入到已經從INSERT
  • 存在表
    INSERT INTO [database_name].[schema_name].[existing_table_name](
        -- the fields in the existing_table_name 
    ) 
    SELECT 
        -- the fields from the first query 
    
    +0

    謝謝標籤和TT - 完美的工作 –

    +0

    @MalcolmHouston更新回答。 –

    2

    只是CROSS JOIN五個查詢,派生表:

    SELECT * FROM (
        Query1 
    ) AS q1 
    CROSS JOIN (
        Query2 
    ) AS q2 
    CROSS JOIN (... 
    

    假設每個單獨的查詢只返回一個行,那麼這個CROSS JOIN應導致只有一行。