Query i need like this - sql

This is my query
SELECT CAL.CALENDAR_NAME,CAL.CALENDAR_ID,CALDAY.CALENDARDAY_DAYID
FROM lms_calendar AS CAL
LEFT JOIN LMS_CALENDARDAY AS CALDAY
ON CAL.CALENDAR_ID = CALDAY.CALENDARDAY_CALENDARID
and I get results like this
CALENDAR_NAME CALENDAR_ID CALENDARDAY_DAYID
-------------------------------------------------- ----------- -----------------
Test 1 1
Test 1 2
Test 1 3
Test 1 4
Test 1 6
But I need like this
calendar_name calendar_dayid calendar_dayid calendar_dayid calendar_dayid calendar_dayid
test 1 2 3 4

Here is a query that uses the PIVOT operator
SELECT calendar_name,
[1] AS calendar_dayid,
[2] AS calendar_dayid,
[3] AS calendar_dayid,
[4] AS calendar_dayid,
[5] AS calendar_dayid
FROM (
SELECT CAL.CALENDAR_NAME,CAL.CALENDAR_ID,CALDAY.CALENDARDAY_DAYID
FROM lms_calendar AS CAL
LEFT JOIN LMS_CALENDARDAY AS CALDAY
ON CAL.CALENDAR_ID = CALDAY.CALENDARDAY_CALENDARID
) AS src
PIVOT (
MAX(calendarday_dayid)
FOR calendarday_dayid IN ([1], [2], [3], [4], [5])
) AS pvt

Related

How to create a pivot tablefor this problem:

This is my original table:
Original table
And I would like it to be as:
CityID | 1 | 2 | 3 | 4 | 5 | 6 | 7
_____________________________________
1024 0800 0900 and so on...
Here is my code, but I get a syntax error near FOR.
select * from
(select SIDURI as CityID, DAY as ArrivalDay, T_FROM as TimeArrival
from RNFIL488) as timingTable
pivot(
timing.SIDURI as CityID
timingTable.T_FROM as TimeArrival
for timing.DAY as ArrivalDay in (
[1],
[2],
[3],
[4],
[5],
[6],
[7]
)
) as pivot_table
Use ROW_NUMBER here:
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY CityID ORDER BY ArrivalDay) rn
FROM RNFIL488
)
SELECT
CityID,
MAX(CASE WHEN rn = 1 THEN TimeArrival END) AS [1],
MAX(CASE WHEN rn = 2 THEN TimeArrival END) AS [2],
MAX(CASE WHEN rn = 3 THEN TimeArrival END) AS [3],
MAX(CASE WHEN rn = 4 THEN TimeArrival END) AS [4],
MAX(CASE WHEN rn = 5 THEN TimeArrival END) AS [5],
MAX(CASE WHEN rn = 6 THEN TimeArrival END) AS [6],
MAX(CASE WHEN rn = 7 THEN TimeArrival END) AS [7]
FROM cte
GROUP BY
CityID;
This assumes that your original source table would always have 7 arrival days per city. If not, then we might have to use a calendar table to bring in the missing data. Also, I am avoiding the PIVOT operator, because often the above approach performs better (and I also find it much easier to read).
I recommend if you don't have a lot data then you can truncate the table and re-fill table. And don't forget your id column should be unique and use auto_increment on id.

Structure the Data horizontally in Sql

Hi I have a query which returns data as below
select
n.Key, np.value
from
Test1 np
join Test2 n on n.Key = np.Key
where
n.NodeKey = 10000002 && np.pKey in (4,6,7,10,12)
which returns data as below
Key value
-------- ------
10000002 2
10000002 0
10000002 2
10000002 True
10000002 1
Test2 is look up Table as below
Key PKey Value
---------------------------------------
10000002 4 2
10000002 6 0
10000002 7 2
10000002 10 True
10000002 12 1
Wanted to change the query so that it should return data as below
NodeKey Value1 Value2 Value3 Value4 Value5
--------------------------------------------------
10000002 2 0 2 True 1
Can you please help me with this.
You may use pivot clause as :
with t as
(
select i.* from Test2 i
)
select [Key] as 'NodeKey',
[4] as 'Value1',
[6] as 'Value2',
[7] as 'Value3',
[10] as 'Value4',
[12] as 'Value5'
from t
pivot
(
max(Value) for PKey in ([4], [6], [7], [10], [12])
) q;
NodeKey Value1 Value2 Value3 Value4 Value5
-------- ------ ------ ------ ------ -------
10000002 2 0 2 True 1
Rextester Demo
You can try using sql-server pivot For structuring data horizontally.
Try below code..
Add another column using row_number() function and Store whole result in temp table
select
n.Key, np.value,
'Value'+convert(varchar(2),ROW_NUMBER() over (partition by [key] order by [key])) as tmpCol
into #tempTable --store result in tmp table
from
Test1 np
join Test2 n on n.Key = np.Key
where
n.NodeKey = 10000002 && np.pKey in (4,6,7,10,12)
then use below pivot code.
select *
from
(
select [key], value,tmpCol
from #tempTable
) src
pivot
(
max(value)
for tmpCol in (value1,value2,value3,value4,value5)
) piv;

How to I convert this column to row format ?

I can use Pivot but my table here has only 2 columns so I don't know how to go about with it. A class has maximum of 5 UserIDs so I want to have a ClassID and associated 5 user names.
UserID ClassID
RK980 5
LO567 5
YY667 5
RT223 5
LT987 3
What I need is :
ClassID User1 User2 User3 User4 User5
5 RK980 LO567 YY667 RT223 NULL
3 LT987 NULL NULL NULL NULL
Thank you !
You can use row_number(). I would then tend to go for conditional aggregation rather than pivot:
select classid,
max(case when seqnum = 1 then userid end) as user1,
max(case when seqnum = 2 then userid end) as user2,
max(case when seqnum = 3 then userid end) as user3,
max(case when seqnum = 4 then userid end) as user4,
max(case when seqnum = 5 then userid end) as user5
from (select t.*, row_number() over (partition by classid order by userid) as seqnum
from t
) t
group by classid;
you can use pivot with row_number
DECLARE #MyTable TABLE (UserID VARCHAR(10), ClassID INT)
INSERT INTO #MyTable VALUES
('RK980', 5 ),
('LO567', 5 ),
('YY667', 5 ),
('RT223', 5 ),
('LT987', 3 )
SELECT ClassID, [1] User1, [2] User2, [3] User3, [4] User4, [5] User5 FROM
(SELECT * ,
ROW_NUMBER() OVER(PARTITION BY ClassID ORDER BY UserID ) AS RN
FROM #MyTable ) SRC
PIVOT(MAX(UserID) FOR RN IN ([1], [2], [3], [4], [5])) PVT
Result:
ClassID User1 User2 User3 User4 User5
----------- ---------- ---------- ---------- ---------- ----------
3 LT987 NULL NULL NULL NULL
5 LO567 RK980 RT223 YY667 NULL

SQL Pivot on two columns

How can I arrange the following result set
meal_type menu_item_id
2 111
2 222
2 333
2 444
2 555
3 666
3 777
3 888
3 999
to
2 3
111 666
222 777
333 888
444 999
555
using pivot or unpivot
The problem with your data - no source for group, PIVOT assumes aggregate function
If you data are small (it is subject for separate topic :-) ), you can create grouping field, using ROW_NUMBER() function. I assume source table name is "test"
with ordered as (
select
row_number() OVER (PARTITION by meal_type order by menu_item_id) num,
* from [test]
)
select
max(case [meal_type] when 2 then [menu_item_id] end) as [2],
max(case [meal_type] when 3 then [menu_item_id] end) as [3]
from ordered group by num
You can achieve the result using ROW_NUMBER and PIVOT:
SELECT [2] ,
[3]
FROM ( SELECT * ,
ROW_NUMBER() OVER ( PARTITION BY meal_type ORDER BY menu_item_id ) R
FROM dbo.Meal
) s PIVOT( MAX(menu_item_id) FOR meal_type IN ( [2], [3] ) ) pvt;

performing operations on columns and rows

I have TWO tables
1) column
2) row
COLUMN TABLE
COLumnID
----------------
1
2
3
4
5
6
7
8
9
ROW TABLE
ROW iD
-------------
100
104
101
99
77
20
10
The final output should look like this:
01.Row 1 2 3 4 5 6 7 8 9
02.----------- ---- ---- ---- ---- ---- ---- ---- ---- ----
03.10 x x x
04.20 x x x x
05.77 x x
06.99 x x x
07.100 x x x x
08.101 x
09.104 x x x x
The challenge is to mark a coordinate, with a value of X, if and only if the row value is divisible by the col value, i.e. it has a modulo of zero. The additional requirements are: the final query must work with random row values and the pivot operator should be used.
The following should do what you are looking for in sql server.
use a CTE to determine where the x should be and then pivot from that CTE
with mq as(select a.rowid
,b.columnid
,case when (a.rowid % b.columnid) = 0 then 'X' else null end as coord
from row_table a
inner join column_table b on 1=1)
select rowid,[1], [2], [3], [4],[5], [6], [7], [8], [9]
from mq
pivot( max(coord) for columnid in ([1], [2], [3], [4],[5], [6], [7], [8], [9])) as pv