Is there a way to count empty fields with this query by adding somewhere Nz, IIf(IsNull()), or something similar?
SELECT DISTINCTROW
mytable.[field1],
mytable.[field2],
mytable.[field3]
FROM mytable
WHERE (((mytable.[field1]) In (SELECT [field1] FROM [mytable] As Tmp GROUP BY
[field1],
[field2],
[field3]
HAVING Count(*)>1 And
[field1] = [mytable].[field1] And
[field2] = [mytable].[field2] And
[field3] = [mytable].[field3]
)));
returns nothing because there are empty fields in field3.
Is there a way to put
IIf(IsNull(field3), "emptyfield", field3)
or something similar somewhere in the query, so that empty field3's will be taken into account?
Try with one or two Nz:
Nz([field1], [mytable].[field1]) = [mytable].[field1]
' or:
[field1] = Nz([mytable].[field1], [field1])
' or:
Nz([field1], [mytable].[field1]) = Nz([mytable].[field1], [field1])
' or, if text:
Nz([field1], "") = Nz([mytable].[field1], "")
' or, if numeric:
Nz([field1], 0) = Nz([mytable].[field1], 0)
Related
I have an issue with my SELECT statement in SSRS.
I want to use an integer to return strings values.
I tried it with this SELECT clause:
SELECT CASE #param = '1' THEN value like '__%' ELSE value like ' '
But it doesn't work, so I tried to use this one instead:
WHERE
((#param = '1' AND value like '__%') OR (#param = '0' AND value = '%'))
The expected result is: When the case is "1" SELECT should return only values which are not ' '
When the case is "0" SELECT should return all values = ' ' + '__%'
Thank you for your help
Your case condition is wrong formatted. You missed WHEN and END .It should be like that:
SELECT CASE WHEN #param = '1' THEN value like '__%' ELSE value like ' ' END
EDIT : As much as I understand you want to see Value if the #param='1' and if not the result will be '__%'. If yes this following CASE usage should be correct:
SELECT CASE WHEN #param = '1' THEN value ELSE value= '__%' END
I fix it my self condition is
((#column = '1' AND column like '__%') OR (#column = '0'AND column like '_%'))
WHERE
((#param = '1' AND value != '') OR (#param = '0'))
just try this
I'm new in sql server and I have WHERE clause like this:
WHERE[D].[IsLocked] = 0
AND(#StartDate IS NULL OR ISNULL([TA].[ModifiedDate], [TA].[CreationDate]) >= #StartDate)
AND(#EndDate IS NULL OR ISNULL([TA].[ModifiedDate], [TA].[CreationDate]) <= #EndDate)
AND((CASE WHEN[T].[TaskStatusId] = '09E02513-00AD-49E3-B442-A9ED2833FB25'
THEN 1 ELSE 0 END) = #Completed)
AND((#FilterEmpKey IS NULL AND[TA].[EmpKey] = #CurrentEmpKey)
OR (ISNULL([TA].[ModifiedAssignedBy], [TA].[AssignatedBy]) = #FilterEmpKey
AND[TA].[EmpKey] = #CurrentEmpKey))
But now I want to add if conditional in order to add more filters at the end of query like:
IF(#FilterEmpGuid IS NOT NULL)
AND[TA].[EmpKey] = #CurrentEmpKey
AND[TA].[AssignatedBy] = #CurrentEmpKey
AND[TA].[EmpKey] = #FilterEmpKey
But I get:
The multi-part identifier [TA].[EmpKey] could not be bound
What am I doing wrong?
IF conditionals are only for use outside sql queries, such as in procedures etc.
In a query itself you are limited to AND, OR and CASE statements, so you will need to rewrite your IF conditional for this:
AND (#FilterEmpGuid IS NULL
OR (
[TA].[EmpKey] = #CurrentEmpKey
AND[TA].[AssignatedBy] = #CurrentEmpKey
AND[TA].[EmpKey] = #FilterEmpKey
))
You could move the additional filter options into a scalar function.
If you know the additional fields that may be filtered, you may be able to get away with something like:
CREATE FUNCTION dbo.ExtendFilter(
#column_value VARCHAR(50), #param_value VARCHAR(50)
)
RETURNS BIT
AS
BEGIN
DECLARE #return BIT = 1; -- default RETURN to 1 ( include ).
IF ( NULLIF( #param_value, '' ) IS NOT NULL )
BEGIN
-- compare the column's value to the param value
IF ( #column_value <> #param_value )
SET #return = 0; -- don't include this record.
END
RETURN #return;
END
GO
And then use it like:
WHERE
{ other WHERE stuff }
AND dbo.ExtendFilter( [TA].[EmpKey], #CurrentEmpKey ) = 1
AND dbo.ExtendFilter( [TA].[AssignatedBy], #CurrentEmpKey ) = 1
AND dbo.ExtendFilter( [TA].[EmpKey], #FilterEmpKey ) = 1
Mind you this is just an example. You'd want to check #pram_value for NULL, etc...
I am using Teradata BTEQ version 15.00. I have the following SQL code. The dynamical SQL is almost there, but the formet is a little off.
.Export Report File = CViews.sql
.Rtitle ''
.Foldline on
.Format Off
.set heading '';
.set heading off;
.set UNDERLINE OFF;
.Omit On 4,5
Select
CASE When ColNo = 1
THEN 'Replace View
$view_db_name.VW_'||Tbl.Tablename||' As locking row for access
Select ('
Else '' END (Title '')
, Cols.Columnname (Title '')
, CASE WHEN RevColNo = 1 THEN ')
From $db_name.'||Tbl.Tablename||';'
Else '' END (Title '')
, Row_Number () Over(Partition By Tbl.Tablename
Order By Cols.ColumnId) As ColNo
, Row_Number () Over(Partition By Tbl.Tablename
Order By Cols.ColumnId Desc) As RevColNo
From DBC.Tables Tbl
Join DBC.Columns Cols
On Tbl.Databasename = Cols.Databasename
And Tbl.Tablename = Cols.TableName
Where Tbl.Databasename = '$db_name'
And Tbl.Tablekind = 'T'
Order By Tbl.Tablename, ColNo
;
.Export Reset
.Run File CViews.sql
Here are the results, but "locking row for access" was cut off, so i got errors when compiling SQL.
Replace View VIEWS_TEST.VW_LOCATION As loc
ID
LOC_TYPE_ID
NAME
LATITUDE
LONGITUDE
ADDR1
ADDR2
CITY
STATE
COUNTRY
) From TABLES_TEST.LOCATION ;
You can see that the "As Loc" was cut off, so i got the following errors:
*** Failure 3707 Syntax error, expected something like a 'SELECT' keyword o
r a 'LOCK' keyword or '(' or a 'TRANSACTIONTIME' keyword between the 'As' key word and the word 'loc'.
Statement# 1, Info =81
*** Total elapsed time was 1 second.
I tried different ways try to make it work, but failed.
Any suggestions?
.Export Report File = CViews.sql
.set width 200
.Rtitle ''
.Foldline on
.Format Off
.set heading '';
.set heading off;
.set UNDERLINE OFF;
.Omit On 4,5
Select
CASE When ColNo = 1
THEN 'Replace View
$view_db_name.VW_'||Tbl.Tablename||' As locking row for access
Select ('
Else '' END (Title '')
, Cols.Columnname (Title '')
, CASE WHEN RevColNo = 1 THEN ')
From $db_name.'||Tbl.Tablename||';'
Else '' END (Title '')
, Row_Number () Over(Partition By Tbl.Tablename
Order By Cols.ColumnId) As ColNo
, Row_Number () Over(Partition By Tbl.Tablename
Order By Cols.ColumnId Desc) As RevColNo
From DBC.Tables Tbl
Join DBC.Columns Cols
On Tbl.Databasename = Cols.Databasename
And Tbl.Tablename = Cols.TableName
Where Tbl.Databasename = '$db_name'
And Tbl.Tablekind = 'T'
Order By Tbl.Tablename, ColNo
;
.Export Reset
.Run File CViews.sql
This is the working version on TD version 15.00.
I added missing "," and change to the dbc.tablesV and dbc.ColumnsV.
.os rm CViews.sql
.Export Report File = CViews.sql
.set width 300
.Rtitle ''
.Foldline on
.Format Off
.set heading '';
.set heading off;
.set UNDERLINE OFF;
.Omit On 4,5
Select
CASE When ColNo = 1
THEN 'Replace View
$view_db_name.VW_'||Tbl.Tablename||' As locking row for access
Select '
Else ', ' END (Title '')
, Cols.Columnname (Title '')
, CASE WHEN RevColNo = 1 THEN '
From $db_name.'||Tbl.Tablename||';'
Else '' END (Title '')
, Row_Number () Over(Partition By Tbl.Tablename
Order By Cols.ColumnId) As ColNo
, Row_Number () Over(Partition By Tbl.Tablename
Order By Cols.ColumnId Desc) As RevColNo
From DBC.TablesV Tbl
Join DBC.ColumnsV Cols
On Tbl.Databasename = Cols.Databasename
And Tbl.Tablename = Cols.TableName
Where Tbl.Databasename = '$db_name'
And Tbl.Tablekind = 'T'
and Tbl.Tablename not like 'WRK_%'
and Tbl.Tablename not like 'ZZ_%'
Order By Tbl.Tablename, ColNo
;
.Export Reset
.Run File CViews.sql
I am trying to select from a single table specific sets of data and then display them grouped under a single field. This however creates a line for each case statement.
I would ideally like to see a single line for each Quote with each of the fields against it.
Would anyone have any ideas how i could improve on what ive done so far?
select
KeyField as Quote,
CASE WHEN FieldName = 'QTY001' THEN AlphaValue ELSE null END as [QTY],
CASE WHEN FieldName = 'CON002' THEN AlphaValue ELSE null END as [Conductors],
CASE WHEN FieldName = 'COP001' THEN AlphaValue ELSE null END as [Copper Size],
CASE WHEN FieldName = 'COR001' THEN AlphaValue ELSE null END as [Core Length],
CASE WHEN FieldName = 'COR002' THEN AlphaValue ELSE null END as [Core Inside],
CASE WHEN FieldName = 'END001' THEN AlphaValue ELSE null END as [End Winding],
CASE WHEN FieldName = 'KV_001' THEN AlphaValue ELSE null END as [KV],
CASE WHEN FieldName = 'KW_001' THEN AlphaValue ELSE null END as [KW],
CASE WHEN FieldName = 'NAM001' THEN AlphaValue ELSE null END as [OEM],
CASE WHEN FieldName = 'SLO001' THEN AlphaValue ELSE null END as [Slots],
CASE WHEN FieldName = 'SPE001' THEN AlphaValue ELSE null END as [Speed],
CASE WHEN FieldName = 'TUR001' THEN AlphaValue ELSE null END as [Turns],
CASE WHEN FieldName = 'TYP001' THEN AlphaValue ELSE null END as [Type/Description]
from
AdmFormData
where
FormType = 'QOT'
add GROUP BY clause
SELECT ...,
MAX(CASE WHEN FieldName = 'QTY001' THEN AlphaValue ELSE null END) as [QTY],
.....
FROM...
WHERE...
GROUP BY KeyField
As an alternative to multiple case when ... statements, you could use SQLServer's PIVOT facility:
select
KeyField as Quote,
[QTY001] as [QTY],
[CON002] as [Conductors],
[COP001] as [Copper Size],
[COR001] as [Core Length],
[COR002] as [Core Inside],
[END001] as [End Winding],
[KV_001] as [KV],
[KW_001] as [KW],
[NAM001] as [OEM],
[SLO001] as [Slots],
[SPE001] as [Speed],
[TUR001] as [Turns],
[TYP001] as [Type/Description]
from
(select KeyField, FieldName, AlphaValue
from AdmFormData
where FormType ='QOT') as s
pivot
(max(AlphaValue) for FieldName in
([QTY001], [CON002], [COP001], [COR001], [COR002], [END001], [KV_001], [KW_001], [NAM001], [SLO001], [SPE001], [TUR001], [TYP001])
) as p
If you have MSSQL 2005 and above you can use PIVOT command:
SELECT KeyField, [QTY001], [CON002], [COR001]
FROM (
SELECT KeyField, FieldName, AlphaValue FROM data
) AS SourceTable
PIVOT (
MAX(AlphaValue)
FOR FieldName IN([QTY001], [CON002], [COR001])
) AS PivotTable
In other case, your solution is the only way to achieve that.
SQLFiddle
I'm trying to grab some data from my SQL database as below;
USE exampleDatabase
SELECT TOP(1) [Name] FROM [Peeps] ORDER BY [Weight] DESC
SELECT TOP(1) [Name] FROM [Peeps] ORDER BY [Age] DESC
The problem is when I read the data I get an error 'Name'.
Dim byWeight As String = sqlReader.GetValue(sqlReader.GetOrdinal("Name"))
Dim byAge As String = sqlReader.GetValue(sqlReader.GetOrdinal("Name"))
How would I read this data as above considering I can't use name twice?
I think you are missing a semi-colon after the first SELECT statement. Here's a sample app I put together (note the semicolon in my sql statement):
var sql = "Select TOP 1 name from sys.columns;"
+ "Select TOP 1 name from sys.objects";
var firstname = string.Empty;
var secondname = string.Empty;
var connString = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
using ( var conn = new SqlConnection( connString ) )
{
conn.Open();
using ( var cmd = new SqlCommand( sql, conn ) )
{
var reader = cmd.ExecuteReader();
if ( reader == null )
return;
if ( reader.Read() )
firstname = reader.GetString( reader.GetOrdinal( "Name" ) );
reader.NextResult();
if ( reader.Read() )
secondname = reader.GetString( reader.GetOrdinal( "Name" ) );
}
}
Response.Write( firstname + "<br />" );
Response.Write( secondname + "<br />" );
You can achieve the same goal as the semi-colon by using the "GO keyword like so:
var sql = "Select TOP (1) name from sys.columns GO "
+ "Select TOP (1) name from sys.objects";
You can use the 'as' keyword to rename columns in your results, like so:
SELECT TOP(1) [Name] AS ByWeight FROM [Peeps] ORDER BY [Weight] DESC
hmmm... well you could make it one select statement....
USE exampleDatabase
SELECT W.[Name] AS W_Name, A.[Name] AS A_Name FROM
(SELECT TOP(1) [Name] FROM [Peeps] ORDER BY [Weight] DESC) W
JOIN (SELECT TOP(1) [Name] FROM [Peeps] ORDER BY [Age] DESC) A
What if you UNION your SQL together into one result set?
USE exampleDatabase
SELECT TOP(1) [Name] FROM [Peeps] ORDER BY [Weight] DESC
UNION ALL
SELECT TOP(1) [Name] FROM [Peeps] ORDER BY [Age] DESC