|No |Type |Num |
| 1 | a | 1 |
| 1 | a | 2 |
| 2 | b | 1 |
| 2 | b | 1 |
| 3 | b | 2 |
| 3 | b | 2 |
I have a Table with columns(No and Type) and I want to create columns(Num) with values. How can I do that in C#?
If you want to split each type into two groups based on no, then you can use window functions:
select t.*,
(case when row_number() over (partition by type order by no) <= 0.5 * count(*) over (partition by type)
then 1 else 2
end) as num
from t;
I'd suggest using dense_rank:
declare #tbl table ([No] int, [Type] varchar(1),[Num] int);
insert into #tbl values
( 1 , 'a' , 1 ),
( 1 , 'a' , 2 ),
( 2 , 'b' , 1 ),
( 2 , 'b' , 1 ),
( 3 , 'b' , 2 ),
( 3 , 'b' , 2 );
select [No], [Type],
dense_rank() over (partition by [Type] order by [Num])
from #tbl
create a method like below and call it
public ExecuteCommand(string columnName,List<string> values)
{
//here 'command' is instance variable of IDbCommand class, to execute command text in database
string sql = "alter table TableName add ColumnName DatatypeOfColumn ";
command.CommandText = sql;
command.ExecuteScalar();
foreach(string value in values)
{
sql = "update table TableName set ColumnName="+ value + " where condition ";
command.CommandText = sql;
command.ExecuteScalar();
}
}
Related
I have a query which is returning two columns which represents the relationship between two entities (direct or indirect), for example the relationships show in the graph to the right would be represented by the data in the table to the right:
| From | To | 1 3 4
|------|----| o----o----o
| 1 | 3 | / \
| 1 | 4 | / \
| 1 | 5 | 2 o o 5
| 2 | 3 |
| 2 | 4 |
| 2 | 5 |
| 3 | 4 | 6 7
| 3 | 5 | o----o
| 6 | 7 |
What I want to do is group this data into a number of sets, equal to the number of distinct graphs described by the relationships (so 2 sets in the above example).
This grouping could happen as part of the database query (T-SQL) or once the data is in memory (C#).
It may not be pretty, but this will group the vertexes properly and only requires edges as a starting point. Note that the order of the vertexes for an edge does not matter.
-- Sample data.
declare #Edges as Table ( Vertex1 Int, Vertex2 Int );
insert into #Edges ( Vertex1, Vertex2 ) values
( 1, 3 ), ( 3, 4 ), ( 3, 2 ), ( 3, 5 ),
( 6, 7 );
select * from #Edges;
-- Create a working table that assigns each vertex to a unique "set".
declare #Sets as Table ( SetId Int, Vertex Int );
insert into #Sets ( SetId, Vertex )
select Row_Number() over ( order by Vertex ), Vertex from (
select distinct Vertex1 as Vertex from #Edges
union
select distinct Vertex2 from #Edges ) as PH;
select * from #Sets;
-- Update the working table to group vertexes into sets:
-- For each vertex update the SetId to the minimum SetId of all of the vertexes one edge away.
-- Repeat until nothing changes.
declare #UpdatedRows as Int = 42;
while #UpdatedRows > 0
begin
update NS
set SetId = MinSetId
from (
select S.SetId, S.Vertex,
( select Min( SetId ) from #Sets where Vertex in (
select S.Vertex union
select Vertex1 from #Edges where Vertex2 = S.Vertex union
select Vertex2 from #Edges where Vertex1 = S.Vertex )
) as MinSetId
from #Sets as S ) as NS
where SetId != MinSetId;
set #UpdatedRows = ##RowCount;
select * from #Sets; -- Show the work as it progresses.
end
-- The SetId values can be collapsed using Dense_Rank .
select Dense_Rank() over ( order by SetId ) as SetId, Vertex
from #Sets;
I want to join two tables and combine it into one but problem is one table is in horizontal format other is in vertical
Below are table structures
Table 1 :
EmpID | Code | Name | Fld1 | Fld2 | Fld3 | Fld4
-- |---- | ------| --- | ---- |---- |----
1 | 1008M | ABC | temp1 | temp2 | temp3 | null
2 | 1039E | XYZ | temp1 | null | null | null
3 | 1040E | TYS | null | null | null | temp6
Table 2 :
EmpID | FieldName | Value
-- |---- | ------
1 | FH | 1000
1 | FB | 1220
2 | FHRA | 3000
2 | FB | 3000
3 | FB | 3000
Desired Output :
EmpID | Code | Name | Fld1 | Fld2 | Fld3 | Fld4 | FH | FB | FHRA
-- |---- | ------| --- | ---- |---- |---- | --- |--- | ----
1 | 1008M | ABC | temp1 | temp2 | temp3 | null |1000 |1210| 0
2 | 1039E | XYZ | temp1 | null | null | null |0 |3000| 3000
3 | 1040E | TYS | null | null | null | temp6|0 |3000| 0
I had tried using Pivot query but it is not working as expected.
You have to use dynamic query as below and you can test is by adding more FieldNames
CREATE TABLE #table1(EmpID INT,
Code VARCHAR(20),
Name VARCHAR(20),
Fld1 VARCHAR(20),
Fld2 VARCHAR(20),
Fld3 VARCHAR(20),
Fld4 VARCHAR(20))
INSERT INTO #table1 VALUES
(1, '1008M','ABC','temp1','temp2','temp3',NULL),
(2, '1039E','XYZ','temp1',NULL,NULL,null),
(3, '1040E','TYS',null,NULL,NULL,'temp6')
CREATE TABLE #table2(EmpID INT, FieldName VARCHAR(20), VALUE INT)
INSERT INTO #table2 VALUES
(1,'FH',1000),
(1,'FB',1220),
(2,'FHRA',3000),
(2,'FB',3000),
(3,'FB',3000)
DECLARE #col VARCHAR(MAX)
DECLARE #sql VARCHAR(MAX)
SELECT #col = COALESCE(#col + ', ','') + QUOTENAME(FieldName)
FROM #table2 GROUP BY FieldName
SELECT #col -- This gives: [FB], [FH], [FHRA]
-- Now setting this #col variable in the Dynamic SQL.
SET #sql = '
select EmpID, Code, Name,Fld1,Fld2,Fld3,Fld4, ' + #col + '
from (select a.EmpID, Code, Name,Fld1,Fld2,Fld3,Fld4, b.FieldName, b.value
from #table1 a
join #table2 b on a.empid=b.empid)p
PIVOT(MAX (VALUE) FOR FieldName IN ( ' + #col + ' )
) AS pvt
'
PRINT #sql
EXEC (#sql)
OUTPUT:
EmpID Code Name Fld1 Fld2 Fld3 Fld4 FB FH FHRA
1 1008M ABC temp1 temp2 temp3 NULL 1220 1000 NULL
2 1039E XYZ temp1 NULL NULL NULL 3000 NULL 3000
3 1040E TYS NULL NULL NULL temp6 3000 NULL NULL
try this working fine
;with demo1 as (
select * from Table_1
), a as
(
SELECT *
FROM Table_2
PIVOT(SUM(value)
FOR Fieldname IN (FH, FB,FHRA)) AS PVTTable
)select demo1.EmpID,demo1.Code,demo1.Name,demo1.Fld1,demo1.Fld2,demo1.Fld3,demo1.Fld4,a.FH,a.FB,a.FHRA
from a inner join demo1 on a.EmpID=demo1.EmpID
OutPut:
declare #temp table(empid int,fh int,fb int, fhra int)
insert into #temp
SELECT *
FROM (
SELECT
empid,fieldname as [field],value as val
FROM dbo.emp
) as s
PIVOT
(
min( val)
FOR [field] IN (fh,fb,fhra)
)AS pvt
select * from #temp join table1
Now join temporary table and table 1.
Try this:
select t1.empid,
t1.code,
t1.fld1,
t1.fld2,
t1.fld3,
t1.fld4,
sum(case when t2.fieldname = 'FH' then t2.value else 0 end) FH,
sum(case when t2.fieldname = 'FB' then t2.value else 0 end) FB,
sum(case when t2.fieldname = 'FHRA' then t2.value else 0 end) FHRA
from table1 t1
left outer join table2 t2
on t1.empid = t2.empid
group by t1.empid,
t1.code,
t1.fld1,
t1.fld2,
t1.fld3,
t1.fld4;
I made this question a while back.
SQL Server making rows into columns
Basically, the person that answered explained very well what I needed to do. However, I encountered a problem
aID| status | group |
-----------------------
1 | acti | group1 |
2 | inac | group2 |
A3 | acti | group1 |
Second Table: This table is fixed. It has around 20 values and the IDs are all numbers
atID| traitname |
------------------
1 | trait1 |
2 | trait2 |
3 | trait3 |
Third Table: This table is used to identify the traits the assets in the first table have. The fields that have the same name as fields in the above tables are obviously linked.
tID| aID | atID | trait |
----------------------------------
1 | 1 | 1 | NAME |
2 | 1 | 2 | INFO |
3 | 2 | 3 | GOES |
4 | 2 | 1 | HERE |
Now, the user wants the program to output the data in the following format:
aID| status | group | trait1 | trait2 | trait 3
-------------------------------------------------
1 | acti | group1 | NAME | INFO | NULL
2 | inac | group2 | HERE | NULL | GOES
A3 | acti | group1 | NULL | NULL | NULL
Now, the problem here is that, as you can see, A3 has no trait. In the final view, I would want A3 to appear completely null in the traits. But it doesn't appear at all, even though it's there. Does anyone know how can I fix this?
Here is the query I am using:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(traitname)
from Table2
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT aid, status, [group],' + #cols + '
from
(
select t1.aid,
t1.status,
t1.[group],
t2.traitname,
t3.trait
from table1 t1
inner join table3 t3
on t1.aid = t3.aid
inner join table2 t2
on t3.atid = t2.atid
) x
pivot
(
max(trait)
for traitname in (' + #cols + ')
) p '
execute sp_executesql #query;
The problem is you are using an INNER JOIN on your tables. An INNER JOIN returns all rows that have matching data in both tables.
Since you want to return everything from Table1, you will alter your query to use a LEFT JOIN instead of the INNER JOIN:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(traitname)
from Table2
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT aid, status, [group],' + #cols + '
from
(
select t1.aid,
t1.status,
t1.[group],
t2.traitname,
t3.trait
from table1 t1
left join table3 t3
on t1.aid = t3.aid
left join table2 t2
on t3.atid = t2.atid
) x
pivot
(
max(trait)
for traitname in (' + #cols + ')
) p '
execute sp_executesql #query;
As a side note, it is difficult to tell what the data types on your join columns are. Your Table1.aid column appears to be a varchar because of the A3 value but your Table3.aid column looks to be an int. If your data types are not the same, then you will need to cast the data on the join similar to -- on t1.aid = cast(t3.aid as varchar(10))
I want to show data like pivot grid. I am right now showing data like following. Please see following image or click on link.
http://screencast.com/t/CWeGy0vi
But I want above data like following:
http://screencast.com/t/ZTb2wk4cdmB
Any suggestion how to achieve this. Starting point. Should I use repeater?
Without seeing your table structure, etc. it is hard to give an exact answer. But I can suggest how you could perform this in SQL. You have some previous questions tagged with sql server so I am guessing that.
You can do this using both an UNPIVOT and a PIVOT:
;with unpiv as
(
select activity,
work,
Location+'_'+col as col,
value
from
(
select activity,
work,
cast(AssignedTasks as varchar(50)) AssignedTasks,
cast(CompletedTasks as varchar(50)) AchievedTasks,
Location
from yourtable
) src
unpivot
(
value
for col in (AssignedTasks, AchievedTasks)
) unpiv
),
piv as
(
select Activity,
work,
London_AssignedTasks,
London_AchievedTasks,
Geneva_AssignedTasks,
Geneva_AchievedTasks,
row_number() over(partition by activity order by activity, work) rn
from unpiv
pivot
(
max(value)
for col in (London_AssignedTasks, London_AchievedTasks,
Geneva_AssignedTasks, Geneva_AchievedTasks)
) piv
)
select case when rn = 1 then activity else '' end activity,
work,
London_AssignedTasks,
London_AchievedTasks,
Geneva_AssignedTasks,
Geneva_AchievedTasks
from piv
See SQL Fiddle with Demo.
The result is:
| ACTIVITY | WORK | LONDON_ASSIGNEDTASKS | LONDON_ACHIEVEDTASKS | GENEVA_ASSIGNEDTASKS | GENEVA_ACHIEVEDTASKS |
-------------------------------------------------------------------------------------------------------------------
| Activity 1 | Task 1 | 10 | 8 | 1 | 1 |
| | Task 2 | 15 | 15 | 100 | 25 |
| Activity 2 | Task 1 | 5 | 5 | 0 | 0 |
| | Task 2 | 0 | 0 | 2 | 2 |
| Activity 3 | Task 1 | 10 | 10 | 50 | 40 |
Edit #1, If you have an unknown or dynamic number of Locations then you can use dynamic SQL to return the result:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT ',' + QUOTENAME(Location+'_'+t.tasks)
from yourtable
cross apply
(
select 'AssignedTasks' tasks
union all
select 'AchievedTasks'
) t
group by location, tasks
order by location
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = ';with unpiv as
(
select activity,
work,
Location+''_''+col as col,
value
from
(
select activity,
work,
cast(AssignedTasks as varchar(50)) AssignedTasks,
cast(CompletedTasks as varchar(50)) AchievedTasks,
Location
from yourtable
) src
unpivot
(
value
for col in (AssignedTasks, AchievedTasks)
) unpiv
),
piv as
(
select Activity,
work,
row_number() over(partition by activity order by activity, work) rn,
'+#cols+'
from unpiv
pivot
(
max(value)
for col in ('+#cols+')
) piv
)
select case when rn = 1 then activity else '''' end activity,
work,
'+#cols+'
from piv'
execute(#query)
See SQL Fiddle with Demo
I'm not an expert at SQL and i'm not even sure if this type of query is doable.
I want to return a count(*) for each "MediaTypeID" for each Month based off of "MediaDate".
Any help would be greatly appreciated!
Thanks.
My Table looks like:
The Table Data looks like:
1 | 1 | Funny Cat Video | 2006-01-25 00:00:00.000
2 | 1 | Funny Dog Video | 2006-01-20 00:00:00.000
3 | 2 | Angry Birds Game | 2006-03-13 00:00:00.000
4 | 4 | Blonde Joke | 2006-03-16 00:00:00.000
5 | 3 | Goofy Clown Picture | 2006-02-27 00:00:00.000
6 | 2 | Racing Game | 2006-02-10 00:00:00.000
7 | 1 | Star Wars Video | 2006-07-15 00:00:00.000
The query would return 12 rows of results for Jan-Dec looking like:
Month | MediaTypeID1Count | MediaTypeID2Count | MediaTypeID3Count | MediaTypeID4Count
Jan | 400 | 255 | 15 | 65
Feb | 100 | 25 | 75 | 35
Mar | 320 | 155 | 50 | 99
Apr | 56 | 0 | 98 | 313
This type of data transformation is known as a PIVOT. SQL Server 2005+ has a pivot function that can be implemented:
select month,
[1] MediaType1_count,
[2] MediaType2_count,
[3] MediaType3_count,
[4] MediaType4_count
from
(
select
mediatypeid,
datename(m, mediadate) Month,
datepart(m, mediadate) monnum
from yourtable
) src
pivot
(
count(mediatypeid)
for mediatypeid in ([1], [2], [3], [4])
) piv
order by monnum
See SQL Fiddle with Demo
If you have an unknown number of values that you want to transpose into columns, then you can use dynamic sql:
DECLARE #cols AS NVARCHAR(MAX),
#colNames AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(mediatypeid)
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select #colNames = STUFF((SELECT distinct ', ' + QUOTENAME(mediatypeid) +' as MediaType' + cast(mediatypeid as varchar(50))+'_Count'
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT month,' + #colNames + ' from
(
select mediatypeid,
datename(m, mediadate) Month,
datepart(m, mediadate) monnum
from yourtable
) x
pivot
(
count(mediatypeid)
for mediatypeid in (' + #cols + ')
) p
order by monnum'
execute(#query)
See SQL Fiddle with Demo
The result will look like:
| MONTH | MEDIATYPE1_COUNT | MEDIATYPE2_COUNT | MEDIATYPE3_COUNT | MEDIATYPE4_COUNT |
----------------------------------------------------------------------------------------
| January | 2 | 0 | 0 | 0 |
| February | 0 | 1 | 1 | 0 |
| March | 0 | 1 | 0 | 1 |
| July | 1 | 0 | 0 | 0 |
I think this may be what you are looking for. The following will simply return the count based off the media type id, then group by year and then its month
Select MediaTypeID, datepart(year, MediaDate), datepart(month, MediaDate), count(*)
From Media
Group by MediaTypeID, datepart(year, MediaDate), datepart(month, MediaDate)
In my opinion, this could be a good challenge for you to start with this code:
Declare #T Table (
MediaID BigInt Primary Key Identity(1, 1)
, MediaTypeID BigInt
, MediaTitle Nvarchar(50)
, MediaDate DateTime
);
Insert #T (
MediaTypeID
, MediaTitle
, MediaDate
) Select 1
, 'Funny Cat Video'
, '2006-01-25 00:00:00.000'
Union
Select 1
, 'Funny Dog Video'
, '2006-01-20 00:00:00.000'
Union
Select 2
, 'Angry Birds Game'
, '2006-03-13 00:00:00.000'
Union
Select 4
, 'Blonde Joke'
, '2006-03-16 00:00:00.000'
Union
Select 3
, 'Goofy Clown Picture'
, '2006-02-27 00:00:00.000'
Union
Select 2
, 'Racing Game'
, '2006-02-10 00:00:00.000'
Union
Select 1
, 'Star Wars Video'
, '2006-07-15 00:00:00.000'
;
Select Month.Title
, Count(Type01_Result.MediaID) As MediaTypeID_1
, Count(Type02_Result.MediaID) As MediaTypeID_2
, Count(Type03_Result.MediaID) As MediaTypeID_3
, Count(Type04_Result.MediaID) As MediaTypeID_4
From (
Select 1 As Id
, 'Jan' As Title
Union
Select 2
, 'Feb'
Union
Select 3
, 'March'
Union
Select 4
, 'April'
Union
Select 5
, 'May'
Union
Select 6
, 'June'
Union
Select 7
, 'July'
Union
Select 8
, 'Aug'
Union
Select 9
, 'Sept'
Union
Select 10
, 'Nov'
Union
Select 11
, 'Oct'
Union
Select 12
, 'Dec'
) As Month
Left Outer Join
#T As Type01_Result
On Type01_Result.MediaTypeID = 1
And DatePart(Month, Type01_Result.MediaDate) = Month.Id
Left Outer Join
#T As Type02_Result
On Type02_Result.MediaTypeID = 2
And DatePart(Month, Type02_Result.MediaDate) = Month.Id
Left Outer Join
#T As Type03_Result
On Type03_Result.MediaTypeID = 3
And DatePart(Month, Type03_Result.MediaDate) = Month.Id
Left Outer Join
#T As Type04_Result
On Type04_Result.MediaTypeID = 4
And DatePart(Month, Type04_Result.MediaDate) = Month.Id
Group By Month.Title
;
The only thing is that you should be carefull about the year value and how many years you wanna include in the output, because this result will give you the summation of all records in each month no matter which year the date of the record is. It may cause some confusion in the result.
(Remember that I always set the tab size to 8 characters in the Options of Management Studio, so I suggest you do that to see the correct style of writing T-SQL)
Hope it helps you.
Cheers