在浪费了大量时间试图让这个查询工作之后,我来这里寻求帮助。
我有一组想要计数的数据。但我想根据条件数成 2 个单独的列
我有下表
CREATE TABLE [dbo].[DIM_DATUM](
[DATE_SK] [int] NULL,
[YEAR_NUMBER] [int] NULL,
[MONTH_NUMBER] [int] NULL,
[MONTH_NAME] [varchar](30) NULL,
[HOLIDAY] [varchar](27) NULL) ON [PRIMARY]
CREATE TABLE [dbo].[RIT](
[RideId] [bigint] NULL,
[DATE_SK] [int] NULL) ON [PRIMARY]
和 im tring 从查询中获取此输出
<table>
<tr>
<th>MONTH_NAME</th>
<th>YEAR_NUMBER</th>
<th>MONTH_NUMBER</th>
<th>RidesYES</th>
<th>RidesNO</th>
<th>RidesALL</th>
</tr>
<tr>
<td>JULY</td>
<td>2017</td>
<td>7</td>
<td>100</td>
<td>200</td>
<td>300</td>
</tr>
</table>
搜索一段时间后,我可以想出这个查询,它或多或少地满足了我的预期
SELECT h.HOLIDAY, h.MONTH_NAME, h.YEAR_NUMBER, h.MONTH_NUMBER,
COUNT(CASE WHEN h.HOLIDAY!= 'NO' THEN 1 END) AS RidesYES,
COUNT(CASE WHEN h.HOLIDAY= 'NO' THEN 1 END) AS RidesNO,
COUNT(*) AS RidesALL
FROM FEIT_RIT f
JOIN DIM_DATUM h ON h.DATE_SK = f.DATE_SK
GROUP BY h.HOLIDAY, h.MONTH_NAME, h.YEAR_NUMBER, h.MONTH_NUMBER
ORDER BY h.YEAR_NUMBER, h.MONTH_NUMBER
但这给了我以下结果: 查询输出的图像
所以基本上,我希望将前 2 行的两个结果放在一行中,同时按月或年分组。这可能吗? 这可以通过事务甚至子查询来实现吗?如果是这样,请帮助我! 提前谢谢你
似乎您不需要holiday
列。并按year - month
进行分组,首先根据年份然后按月分组。
SELECT h.MONTH_NAME, h.YEAR_NUMBER, h.MONTH_NUMBER,
COUNT(CASE WHEN h.PUBLIEKE_FEESTDAG != 'NO' THEN 1 END) AS RidesYES,
COUNT(CASE WHEN h.PUBLIEKE_FEESTDAG = 'NO' THEN 1 END) AS RidesNO,
COUNT(*) AS RidesALL
FROM FEIT_RIT f
JOIN DIM_DATUM h ON h.DATE_SK = f.DATE_SK
GROUP BY h.YEAR_NUMBER, h.MONTH_NAME, h.MONTH_NUMBER
ORDER BY h.YEAR_NUMBER, h.MONTH_NUMBER