This MUST be a simple one, I've very reluctantly asked this question - but I can't work it out. I have a query which (in a roundabout way) returns 2 counts:
这一定是一个简单的问题,我很不情愿地问了这个问题——但我做不出来。我有一个查询(以迂回的方式)返回2个计数:
Col1 | COL2
123 456
But I need to return:
但我需要回来:
123 | COL1
456 | COL2
What I've Tried
我已经试过
I've looked at UNPIVOT
but since these are simple (independent) rows it seems unnecessary (i.e. I don't need to pivot/unpivot an identifier or anything).
我已经研究了UNPIVOT,但由于它们是简单的(独立的)行,它看起来是不必要的(也就是说,我不需要一个标识符或任何东西)。
The Query
查询
SELECT SUM(CASE WHEN [CONDITION] THEN 1 ELSE 0 END) as Col1,
SUM(CASE WHEN [CONDITION] THEN 1 ELSE 0 END) as Col2
FROM MyTable
1 个解决方案
#1
2
Use a UNION
:
使用一个联盟:
SELECT COL1 AS VALUE, 'COL1' AS COL
FROM yourTable
UNION ALL
SELECT COL2 AS VALUE, 'COL2' AS COL
FROM yourTable
If you want to select from the entire UNION
query, you can wrap it and select out:
如果您想要从整个UNION查询中进行选择,可以将其封装并选择:
SELECT t.VALUE,
t.COL
FROM
(
SELECT COL1 AS VALUE, 'COL1' AS COL
FROM yourTable
UNION ALL
SELECT COL2 AS VALUE, 'COL2' AS COL
FROM yourTable
) t
#1
2
Use a UNION
:
使用一个联盟:
SELECT COL1 AS VALUE, 'COL1' AS COL
FROM yourTable
UNION ALL
SELECT COL2 AS VALUE, 'COL2' AS COL
FROM yourTable
If you want to select from the entire UNION
query, you can wrap it and select out:
如果您想要从整个UNION查询中进行选择,可以将其封装并选择:
SELECT t.VALUE,
t.COL
FROM
(
SELECT COL1 AS VALUE, 'COL1' AS COL
FROM yourTable
UNION ALL
SELECT COL2 AS VALUE, 'COL2' AS COL
FROM yourTable
) t