SQL查询 - 获取子查询结果而不是列

时间:2012-10-15 10:44:34

标签: sql sql-server-2008 subquery

我检查了搜索,但似乎没有人回答这个问题。我希望它虽然很简单: 我有一个查询导致两列,但我需要它导致两行..任何人都知道如何?

这是查询:

               SELECT        (SELECT        COUNT(Id) AS Expr1
                      FROM            Table
                      WHERE        (Description LIKE 'door%')) AS Door,
                         (SELECT        COUNT(Id) AS Expr1
                           FROM            Table AS Table_1
                           WHERE        (Description LIKE 'window%')) AS Window

我GET的结果(当然):

[Door]     [Window]
56         34

我想要的结果如下:

[OPTION]    [NROfRecords]
Door        56
Window      34

任何想法?提前致谢!

4 个答案:

答案 0 :(得分:2)

您可以使用UNPIVOT,我建议将查询重写为以下内容:

select *
from
(
  SELECT 
    sum(case when Description LIKE 'door%' then 1 else 0 end) Door,
    sum(case when Description LIKE 'window%' then 1 else 0 end) Window
  from Table1
) x
unpivot
(
  NrOfRecords
  for [Option] in (Door,  Window)
) u

请参阅SQL Fiddle with Demo

答案 1 :(得分:1)

SELECT 'Door'   AS Option, COUNT(id) FROM table WHERE description LIKE 'door%'
UNION ALL
SELECT 'Window' AS Option, COUNT(id) FROM table WHERE description LIKE 'window%'

... OR

WITH
  filtered AS
(
  SELECT
    CASE WHEN description LIKE 'door%'   THEN 'Door'
         WHEN description LIKE 'window%' THEN 'Window'
                                         ELSE 'Other' END AS option,
    *
  FROM
    yourTable
  WHERE
       description LIKE 'door%'
    OR description LIKE 'window%'
)
SELECT
  option,
  COUNT(id)
FROM
  filtered
GROUP BY
  option

或者...

SELECT
  lookup.option,
  COUNT(id)
FROM
(
  SELECT 'door'   AS option
  UNION ALL
  SELECT 'window' AS option
)
  AS lookup
INNER JOIN
  yourTable
    ON yourTable.description LIKE lookup.option + '%'
GROUP BY
  lookup.option

答案 2 :(得分:0)

select 
    case when description like 'door%' then 'door'
         when description like 'window%' then 'window' 
         else '' 
    end as [desc],
    count(id)
from table
where description like 'door%' or description like 'window%'
group by 
(
    case when description like 'door%' then 'door'
    when description like 'window%' then 'window' else '' end
)

答案 3 :(得分:-1)

这样的解决方案遵循DRY原则 - 您不会在任何地方重复门或窗。 在这里添加其他实体也很容易,因此您不需要重复逻辑。

select
    C.description,
    count(*)
from Table1 as t
    inner join (
        select 'door%', 'Door' union all
        select 'window%', 'Window'
    ) as C(pattern, description) on t.description like c.pattern
group by C.description

<强> sql fiddle demo