2015-12-16 112 views
-1

我想通過不同站點上的車輛註冊牌進行分組,車輛進入站點的次數是多少次,我正在使用SQL Server 2008 R2。按SQL Server中3列的範圍組

我的數據是這樣的:

Streetname vrm 0-9 10-19 19-20 
Ebbw vale xyz  1  15  30 
Peel Center M89GW 6  35  45 

這是我的查詢:

Select 
    t.t_street_name, COUNT(t_vrm) as MultipleEntries 
from 
    (select 
     case 
      when count(t_vrm) between 0 and 9 then '0-9' 
      when count(t_vrm) between 10 and 19 then '10-19' 
      when count(t_vrm) between 20 and 29 then '20-29' 
      when count(t_vrm) between 30 and 39 then '30-39' 
      when count(t_vrm) between 40 and 49 then '40-49' 
      when count(t_vrm) between 50 and 59 then '50-59' 
     end as t_vrm 
    from 
     [ICPS].[dbo].[tickets]) t 
where 
    convert (datetime, t.t_date_time_issued, 101) between convert(datetime, '2015/11/15', 101) and convert (datetime, '2015/12/17', 101) 
Group By 
    t_vrm, t.t_street_name 

我得到這個錯誤

無效的列名t_street_name

+0

,你能否告訴了' [ICPS]。[dbo]。[門票]'結構? –

+0

你的查詢是搞砸了。你在沒有'group by'的子查詢中有count()'。然後你在外部查詢中有'group by'。所以,有很多問題。你想做什麼? –

回答

1

我看到您的問題,您創建了一個子查詢作爲表,並且您正在嘗試獲取未在子查詢中選中的列。您需要添加該列t_street_name以便外部選擇看到它。

所以試試這種方式。在此猜測,缺少的列是來自[ICPS].[dbo].[tickets]表。所以

Select t.t_street_name,COUNT(t_vrm) as MultipleEntries 
    from (select case 
       when count(t_vrm) between 0 and 9 then '0-9' 
       when count(t_vrm) between 10 and 19 then '10-19' 
       when count(t_vrm) between 20 and 29 then '20-29' 
       when count(t_vrm) between 30 and 39 then '30-39' 
       when count(t_vrm) between 40 and 49 then '40-49' 
       when count(t_vrm) between 50 and 59 then '50-59' 
       end as t_vrm, 
       t_street_name -- HERE YOU FORGOT HERE 
      from 
       [ICPS].[dbo].[tickets] 
      group by t_street_name 
     )t     
     where convert (datetime,t.t_date_time_issued,101) 
        between convert(datetime,'2015/11/15',101) 
         and convert (datetime,'2015/12/17',101) 
    Group By t_vrm, t.t_street_name 

當你使用它成爲你的表,因此對外部查詢列是隻有你的子查詢選擇的,對你的情況只是t_vrm

按照該@GordonLinoff一個子查詢發表評論我已經來看看你的查詢,看看那是你真正想要的是所謂的樞轉表這是把行轉換成列,所以你的問題正確的查詢是:

Select t.*, 
    from (select t_street_name, 
       case when count(t_vrm) between 0 and 9 then '0-9' end as "0-9", 
       case when count(t_vrm) between 10 and 19 then '10-19' end as "10-19", 
       case when count(t_vrm) between 20 and 29 then '20-29' end as "20-29", 
       case when count(t_vrm) between 30 and 39 then '30-39' end as "30-39", 
       case when count(t_vrm) between 40 and 49 then '40-49' end as "40-49", 
       case when count(t_vrm) between 50 and 59 then '50-59' end as "50-59" 
      from [ICPS].[dbo].[tickets] 
     where convert (datetime,t.t_date_time_issued,101) 
        between convert(datetime,'2015/11/15',101) 
         and convert (datetime,'2015/12/17',101) 
     group by t_street_name 
     )t