Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 regarding to Union results

Author  Topic 

eirikr_1
Starting Member

27 Posts

Posted - 2013-02-14 : 20:39:26
the results orders are messed up. Need help...Thanks
my union query

SELECT count(distinct IAV) as IavCount, '1/1/2013- 1/5/2013' as EachWeek
FROM IavInfo
WHERE IAV <> 'N/A'
AND ScanDate BETWEEN '1/1/2013' AND '1/5/2013' union
SELECT count(distinct IAV) as IavCount, '1/6/2013- 1/12/2013' as EachWeek
FROM IavInfo WHERE IAV <> 'N/A'
AND ScanDate BETWEEN '1/6/2013' AND '1/12/2013' union
SELECT count(distinct IAV) as IavCount, '1/13/2013- 1/19/2013' as EachWeek
FROM IavInfo WHERE IAV <> 'N/A'
AND ScanDate BETWEEN '1/13/2013' AND '1/19/2013' union
SELECT count(distinct IAV) as IavCount, '1/20/2013- 1/26/2013' as EachWeek
FROM IavInfo WHERE IAV <> 'N/A'
AND ScanDate BETWEEN '1/20/2013' AND '1/26/2013' union
SELECT count(distinct IAV) as IavCount, '1/27/2013- 1/31/2013' as EachWeek
FROM IavInfo WHERE IAV <> 'N/A'
AND ScanDate BETWEEN '1/27/2013' AND '1/31/2013'

and the result is
0 1/1/2013- 1/5/2013
0 1/13/2013- 1/19/2013
0 1/20/2013- 1/26/2013
0 1/27/2013- 1/31/2013
4 1/6/2013- 1/12/2013

I would like the result
0 1/1/2013- 1/5/2013
4 1/6/2013- 1/12/2013
0 1/13/2013- 1/19/2013
0 1/20/2013- 1/26/2013
0 1/27/2013- 1/31/2013

Please help

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2013-02-14 : 21:57:04
here is one way.

; with daterange as
(
SELECT frDate = convert(date, '2013-01-01'), toDate = convert(date, '2013-01-05') union all
SELECT frDate = '2013-01-06', toDate = '2013-01-12' union all
SELECT frDate = '2013-01-13', toDate = '2013-01-19' union all
SELECT frDate = '2013-01-20', toDate = '2013-01-26' union all
SELECT frDate = '2013-01-27', toDate = '2013-01-31'
)
SELECT count(distinct IAV) as IavCount,
convert(varchar(10), frDate, 101) + ' - ' + convert(varchar(10), toDate, 101) as EachWeek
FROM IavInfo i
INNER JOIN daterange d ON i.ScanDate BETWEEN frDate AND toDate
WHERE IAV <> 'N/A'
GROUP BY frDate, toDate
ORDER BY frDate



KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-02-14 : 23:16:11
ORDER BY DATEDIFF(dd,0,RTRIM(LEFT(EachWeek,CHARINDEX('-',EachWeek)-1)))

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

eirikr_1
Starting Member

27 Posts

Posted - 2013-02-15 : 12:49:10
Thank you everyone for help.
Hey Khtan, your query reutrns a row only. How can i get all others?
Go to Top of Page
   

- Advertisement -