1

我检查了搜索,但似乎没有人回答这个问题..我希望它非常简单:我有一个查询结果为两列,但我需要它产生两行..有人知道怎么做吗?

这是查询:

               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

我得到的结果是(当然):

[Door]     [Window]
56         34

我想要的结果如下:

[OPTION]    [NROfRecords]
Door        56
Window      34

有任何想法吗?提前致谢!

4

4 回答 4

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

于 2012-10-15T10:49:47.467 回答
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

Or...

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
于 2012-10-15T10:47:29.473 回答
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
)
于 2012-10-15T10:47:58.650 回答
-1

Solution like this is following DRY principle - you do not repeat Door or Window anywhere. It also easy to add another entities here, so you do not repeat a logic.

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

于 2012-10-15T10:48:17.293 回答