HI,
I want to create a datagridview in a form with 4 columns basically which has only 2 column headers, ie i want to merge only the column headers of 2 columns.
Thanks in advance
pls, check if code from this SO question winform - merging datagridview headers and its answers would work for you
i assume you're binding to a sql-provided datatable, right? If so, why not combine the results in your datatable and bind that. Simpler, with less programming.
E.g.
SELECT col1 + ' ' + col2, col3 + ' ' + col4 FROM someTable ORDER BY col1 + ' ' + col2
Fancier version:
SELECT col1 + ' ' + col2 AS 'Fancy Column Name 1' ,
col3 + ' ' + col4 AS 'Fancy Column Name 2
FROM someTable ORDER BY col1 + ' ' + col2
Related
This is my sample table:
TableName ColumnName
Sample Name
Sample MiddleName
Sample LastName
I'm trying to test the following code:
SELECT 'SELECT ' +
CASE WHEN TableName IS NOT NULL AND ColumnName IS NOT NULL THEN TableName_ColumnName
WHEN TableName IS NOT NULL AND ColumnName IS NULL THEN TableName_NULL
ELSE ISNULL(ColumnName, 'NULL')
END
+ ' FROM [TestDB].[dbo].' + TableName
FROM [TestDB].[dbo].[TestTable] WHERE TableName = 'Sample'
Here is a result I'm getting from the above, it's including the SELECT and 'FROM [TestDB].[dbo]' + TableName for each row which is not what I want:
SELECT Sample_Name FROM [TestDB].[dbo].Sample
SELECT Sample_MiddleName FROM [TestDB].[dbo].Sample
SELECT Sample_LastName FROM [TestDB].[dbo].Sample
The ideal result should look like this:
SELECT
Sample_Name
Sample_MiddleName
Sample_LastName
FROM [TestDB].[dbo].Sample
What am I missing?
If I understood correctly from your question you need a solution like this:
WITH TableNamesCTE AS
(
SELECT DISTINCT TableName
FROM TestTable
)
SELECT 'SELECT ' +
(SELECT STRING_AGG(CASE WHEN TableName IS NOT NULL AND ColumnName IS NOT NULL THEN CONCAT(TableName, '_', ColumnName)
WHEN TableName IS NOT NULL AND ColumnName IS NULL THEN CONCAT(TableName, '_NULL')
ELSE ISNULL(ColumnName, 'NULL')
END, ',')
FROM [TestTable] TT
WHERE TT.TableName = TN.TableName)
+ ' FROM [TestDB].[dbo].' + TableName
FROM TableNamesCTE TN
WHERE TN.TableName = 'Sample';
I have separated table names with CTE, so if you have 100 tables, then this query will produce 100 query strings. Once you have all tables prepared then in the second part of the query you will get aggregated all these things.
SQL Server command STRING_AGG is available from 2017 version. For more information: https://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-ver15
I want to calculate the cell values based on the given formula in each row.
Input record is:
Expected ouput is:
First thing is your formula is not correct. As I understand there is unique row for each sl. And to do the sum of col1 and col2 correct formula is (col1 + col2). So correct that thing first.
After that you may implement this using dynamic sql as
create table tab_sum ( id int, col1 int, col2 int, col varchar(max) )
insert into tab_sum ( id, col1, col2, col )
values ( 1, 3, 5, '(col1 + col2)' )
, ( 2, 4, 6, '(col1 + col2)' )
DECLARE #query NVARCHAR(MAX) = '';
WITH CTE_DistinctFormulas AS
(
SELECT DISTINCT col as Formula FROM tab_sum
)
SELECT #query = #query + '
UNION ALL
SELECT id, col1, col2, col, ' + Formula + ' AS CalcValue FROM tab_sum WHERE col = ''' + Formula + ''' '
FROM CTE_DistinctFormulas;
SET #query = STUFF(#query,1,12,'');
PRINT #query;
EXEC (#query);
Or if editing formula is not an option for you then you may try this, But make sure you have only one row for each id and its corresponding values otherwise it will sum all of the similar rows in one.
create table tab_sum ( id int, col1 int, col2 int, col varchar(max) )
insert into tab_sum ( id, col1, col2, col )
values ( 1, 3, 5, 'sum(col1 + col2)' )
, ( 2, 4, 6, 'sum(col1 + col2)' )
DECLARE #query NVARCHAR(MAX) = '';
WITH CTE_DistinctFormulas AS
(
SELECT DISTINCT col as Formula FROM tab_sum
)
SELECT #query = #query + '
UNION ALL
SELECT id, col1, col2, col, ' + Formula + ' AS CalcValue FROM tab_sum WHERE col = ''' + Formula + ''' group by id, col1, col2, col '
FROM CTE_DistinctFormulas;
SET #query = STUFF(#query,1,12,'');
PRINT #query;
EXEC (#query);
I think you want something like this:
select *,case when row_cal like '%1%' and row_cal like '%2%' then value1 + value2
when row_cal like '%1%' and row_cal like '%3%' then value1 + value3
end as result from YourTable
Did you have a look at the case/ when expression? See MS doc: CASE
So your query would be somthing like:
SELECT sl, audience_1, audience_2, audience_3,
CASE WHEN audience_3 > 0 THEN audience_1 + audience_3
ELSE audience_1 + audience_2
END audience_total
FROM audience
;
You did not provide the criteria, so I had to guess :-)
(I did not run the query since I had no server handy :-) )
UPDATE after comment by OP:
If you have 71 different columns for audience in the same table you have a differnt issue imho.
Then my solution would be:
split out the audience number to a detail table with sl,
audience_type and audience_count
create a audience_calc_config table with two columns calc_method and audience_type
for each different calculation and audience type add an entry to the above
table
remove formula from original table and replace with appropriate
calc_method
Then run a simple select with a JOIN, GROUP BY sl and SUM(audience)
(Of course it would be even nicer to split the audience_calc to a
master/ detail, so you can have a foreign key...)
Please help me understand how to implement the ROLLUP on this pivot table.
I have been looking over several of the other written solutions to my requirement, but I seem to be missing something when I apply them to my situation. SQL is not my strength, but I feel like I understand more each time I accomplish something.
Creating this pivot statement below was a little struggle since I need to work with dynamic fields to summarize the total for different dID depending on the cID that the report is running.
I am using a method to dynamically create the NVARCHAR that will represent the columns I am applying SUM to in the pivot table. I've attempted to use the ROLLUP function as part of the GROUP BY condition of the SELECT without success.
The general layout I would like is something like this below. Additionally, I have a second pivot with the same dID from a different dataset that I would like to merge the Totals from both into a new table, and create a GrandTotal. I imagine this would be best accomplished with a UNION
dID, dName, qID's, dID_Total
1, A, 100-113, #
2, B, 100-113, #
3, C, 100-113, #
4, D, 100-113, #
5, E, 100-113, #
DECLARE #sID int = 100
DECLARE #cID int = 5
DECLARE #ColumnName AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT #ColumnName = ISNULL(#ColumnName + ',', '') + QUOTENAME(qID)
FROM(SELECT qID FROM qTable WHERE cID = #cID) AS QuestionID
DECLARE# PivotTableSQL NVARCHAR(MAX)
SET# PivotTableSQL = N'
SELECT
dID, dName, ' + #ColumnName + '
FROM (
SELECT dID, dName, qID, weighted AS [score]
FROM sourceTable
WHERE sID = ' + CAST(#sID AS nvarchar(8)) + ' AND cID = ' + CAST(#cID AS nvarchar(8)) + '
) AS PivotData
PIVOT (
SUM(score)
FOR [qID] IN (
' + #ColumnName + '
)
) AS PivotTable
GROUP BY
dID, dName,' + #ColumnName
EXECUTE(#PivotTableSQL)
I currently have a piece of code that pivots a table in which the row data is inserted dynamically. The code is shown below:
CREATE TABLE Table1
([empname] varchar(6), [empqual] varchar(10), [emprank] int, [empexp] int)
INSERT INTO Table1
([empname], [empqual], [emprank], [empexp])
VALUES
('Joyce', 'UNIVERSITY', 1, 11),
('Angela', 'MASTERS', 2, 10),
('Lily', 'MASTERS', 3, 9),
('Sasha', 'UNIVERSITY', 3, 9),
('Harry', 'UNIVERSITY', 3, 9)
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
SET #cols = STUFF((SELECT distinct ',' + 'Column' + CONVERT(VARCHAR,Row_Number() OVER (Order By emprank))
FROM Table1 c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET #query = '
SELECT *
FROM
(
SELECT ''Column'' + CONVERT(VARCHAR,Row_Number() OVER (Order By emprank)) AS Columns,
CONVERT(VARCHAR,empname) as e
FROM Table1
) p
PIVOT
(
MAX (e)
FOR Columns IN
(
' + #cols + ' )
) as pvt
UNION
SELECT *
FROM
(
SELECT ''Column'' + CONVERT(VARCHAR,Row_Number() OVER (Order By emprank)) AS Columns,
CONVERT(VARCHAR,empqual) as e
FROM Table1
) p
PIVOT
(
MAX (e)
FOR Columns IN
(
' + #cols + ' )
) as pvt
UNION
SELECT *
FROM
(
SELECT ''Column'' + CONVERT(VARCHAR,Row_Number() OVER (Order By emprank)) AS Columns,
CONVERT(VARCHAR,emprank) as e
FROM Table1
) p
PIVOT
(
MAX (e)
FOR Columns IN
(
' + #cols + ' )
) as pvt
UNION
SELECT *
FROM
(
SELECT ''Column'' + CONVERT(VARCHAR,Row_Number() OVER (Order By emprank)) AS Columns,
CONVERT(VARCHAR,empexp) as e,
FROM Table1
) p
PIVOT
(
MAX (e)
FOR Columns IN
(
' + #cols + ' )
) as pvt
'
EXECUTE (#query)
The result of the above code is as shown below:
Column1 Column2 Column3 Column4 Column5
1 2 3 3 3
11 10 9 9 9
Joyce Angela Lily Sasha Harry
UNIVERSITY MASTERS MASTERS UNIVERSITY UNIVERSITY
Now, my application requires that I display each of the columns in this table separately, i.e. each of the columns, and not rows, of this table needs to be exported from this table and transferred, possibly into a temporary table, from which it can be displayed easily.
I am well aware of the fact that relational DBs are designed in such a way so as to consider rows, not columns, as individual entities. However, I am constrained by the application on which I am working, which requires code that extracts the data in this table column-wise so that they can be displayed separately.
How would I go about doing this?
This is a terminology overlap.
In SQL, "row" means (roughly) a single entity, and "column" means a property on the entities.
In UI, "row" means data arranged horizontally, and "column" means data arranged vertically.
Your requirement is that you should display your entities vertically. So, retrieve your entities (SQL rows) and then add code in your application to display this data in UI columns. It's unfortunate and perhaps confusing that the terms are the same here, but remember, your database structure (and choice of terminology) is completely irrelevant to your UI layout.
As to what code in your application is required to display the data... well, you haven't even told us what language it's in, so I can't help there.
I need to bring values together and copy it to a diffrent column.
COLUMN 1 | COLUMN 2 | COLUMN 3 | COLUMN 4
Hallo out there Hallo out there
My NULL name is My name is
I'm a rabbit I'm a rabbit
How to merge column 1, 2, 3 and copy it to column4 separated with space.
Columns can be null.
UPDATE dbo.table
SET column4 = COALESCE(column1, '')
+ COALESCE(' ' + column2, '')
+ COALESCE(' ' + column3, '');
SQL Server 2012
UPDATE table
SET Column4 = CONCAT(Column1 + ' ', Column2 + ' ', Column3)
Just use + sign
select ISNULL([COLUMN 1],'')+' ' +
isnull([COLUMN 2],'')+' ' +
isnull([COLUMN 3],'')
from your_table
Using ISNULL
UPDATE table
SET Column4 =
ISNULL(Column1+' ','') +
ISNULL(Column2+' ','') +
ISNULL(Column3,'')
Or you could consider using a calculated column.
select isnull(convert(varchar(255),[COLUMN1]),'')+' '+isnull(convert(varchar(255),[COLUMN2]),'')+' '+isnull(convert(varchar(255),[COLUMN3]),'')
from table
UPDATE table
SET COLUMN4 = isnull(convert(varchar(255),[COLUMN1]),'')+' '+isnull(convert(varchar(255),[COLUMN2]),'')+' '+isnull(convert(varchar(255),[COLUMN3]),'')
Above codes may not work depending on datatypes so you may convert it to varchar before.
update yourtable SET COlumn4= ltrim(rtrim(isnull([COLUMN 1],'') +' '+isnull([COLUMN 2],'') +' '+ isnull([COLUMN 3],'')))